flatMapCompletable 不调用给定的 Action

flatMapCompletable does not call the given Action

我原以为 flatMapCompletable 会在 Completable 正常完成时调用给定的 Action。但是,它并不像我想的那样工作。这是一个简单的例子:

    PublishProcessor<String> processor = PublishProcessor.create();

    processor.flatMapCompletable(s2 -> {
        System.out.println("s2 " + s2);
        return Completable.complete();
    }).subscribe(() -> {
        System.out.println("done"); // it does not come here
    });

这是预期的行为吗?如果是这样,我如何检查可完成任务是否完成? Completable.complete().doFinally()?

您需要调用 processor.onComplete(); 才能完成操作。这是因为在侦听传入事件时您仍然订阅了主题。

Flowable 正常完成

    Flowable.just(1).flatMapCompletable(s2 -> {
        System.out.println("s2 " + s2);
        return Completable.complete();
    }).subscribe(() -> {
        System.out.println("done"); // it does come here
    });

正如 Alexander 所指出的,你什么都得不到的原因是 PublishProcessor 永远不会完成。

JavaDocflatmapCompletable 个注释如下。

Maps each element of the upstream Observable into CompletableSources, subscribes to them and waits until the upstream and all CompletableSources complete.

所以你必须确保上游 Observable 和所有 CompletableSources 完成接收任何事件。

谢谢。