您好我发现很少有手册说明:默认情况下Rx是单线程的。
你可以在这里https://github.com/Froussios/Intro-To-RxJava/blob/master/Part%204%20-%20Concurrency/1.%20Scheduling%20and%20threading.md找到这个短语,但这不仅仅是一个获取它的地方。
我试着用它玩一下,实际上是多线程的。这是我试过的简单代码:
Observable<Long> values1 = Observable.interval(1000, TimeUnit.MILLISECONDS);
values1.subscribe(
v -> {
System.out.println("Received 1: " + v + ", Thread: " + Thread.currentThread().getName());
},
e -> System.out.println("Error: " + e),
() -> System.out.println("Completed")
);
Observable<Long> values2 = Observable.interval(1000, TimeUnit.MILLISECONDS);
values2.subscribe(
v -> {
System.out.println("Received 2: " + v + ", Thread: " + Thread.currentThread().getName());
},
e -> System.out.println("Error: " + e),
() -> System.out.println("Completed")
);
values1.subscribe(
v -> {
System.out.println("Received 3: " + v + ", Thread: " + Thread.currentThread().getName());
},
e -> System.out.println("Error: " + e),
() -> System.out.println("Completed")
);
System.in.read();
这里只有两个观察者和3个读者。此代码输出:
Received 1: 0, Thread: RxComputationThreadPool-1
Received 3: 0, Thread: RxComputationThreadPool-3
Received 2: 0, Thread: RxComputationThreadPool-2
Received 1: 1, Thread: RxComputationThreadPool-1
Received 2: 1, Thread: RxComputationThreadPool-2
Received 3: 1, Thread: RxComputationThreadPool-3
...
正如我从输出中看到的,每个读者都接受了新的线程,我从未明确提到为每个新观察者创建新线程。那么这个单线程默认行为是不是?我想念某个地方吗?
答案 0 :(得分:1)
RxJava是单线程的,它有两个部分:
observeOn
和interval
。由于您的示例使用interval
,这需要阻塞才能真正实现单线程,因此使用了更有效的基于调度程序的解决方案。Callable<T>
和Future<T>
。onNext
的调用不会发生在平行。这可能是“RxJava是单线程”规则的基础,因为它本身不支持并行操作。 RxJava2
添加了ParallelObservable
系列操作以支持真正的并行性。