如何停止主线程并有可能停止 RxJava 中的所有流程

How to stop main thread and get possibility to stop all flow in RxJava

我需要停止主线程并获得停止流的可能性

我用

.subscribe();

主线程没有停止,但我得到了 Disposable,我可以用它来停止所有流程

但是当我使用

.blockingSubscribe();

它return无效,我无法停止所有可流动的,但主线程已停止

我可以用

.filter(s -> !stopService.get())

但似乎找到了更好的方法来停止所有可流动的

  1. 是否有另一种方法来停止主线程并有可能停止所有可流动的线程?

  2. 也许有一种方法可以使用 Disposable 和一些主线程阻塞运算符?

It return void, and i cant stop all flowable

返回 Disposable 没有意义,因为 blockingSubscribe 仅在流终止时 returns,因此在 Disposable 之后处理它没有任何效果。

您可以使用 takeUntilPublishProcessor 来请求终止,同时使用 blockingSubscribe

var stop = PublishProcessor.create();

// hand the processor to something that would signal it to stop, e.g.,

ForkJoinPool.commonPool().submit(() -> {
    System.out.println("Press ENTER to stop");
    System.in.read();
    stop.onComplete();
    return null; // to get submit(Callable)
});

source
.takeUntil(stop)
.blockingSubscribe();

一般来说,如果你想阻塞 Java 主线程,你需要一个异步信号来解除阻塞。