【发布时间】:2019-01-10 11:50:38
【问题描述】:
我已经阅读了关于blockingSubscribe() 和subscribe() 的解释,但我既不能写也不能找到例子来看看它们的区别。似乎这两者的工作方式相同。有人可以提供这两个的例子,最好是Java。
【问题讨论】:
我已经阅读了关于blockingSubscribe() 和subscribe() 的解释,但我既不能写也不能找到例子来看看它们的区别。似乎这两者的工作方式相同。有人可以提供这两个的例子,最好是Java。
【问题讨论】:
blockingSubscribe 阻塞当前线程并在那里处理 incomnig 事件。您可以通过运行一些异步源来看到这一点:
System.out.println("Before blockingSubscribe");
System.out.println("Before Thread: " + Thread.currentThread());
Observable.interval(1, TimeUnit.SECONDS)
.take(5)
.blockingSubscribe(t -> {
System.out.println("Thread: " + Thread.currentThread());
System.out.println("Value: " + t);
});
System.out.println("After blockingSubscribe");
System.out.println("After Thread: " + Thread.currentThread());
subscribe 没有这样的限制,可以在任意线程上运行:
System.out.println("Before subscribe");
System.out.println("Before Thread: " + Thread.currentThread());
Observable.timer(1, TimeUnit.SECONDS, Schedulers.io())
.concatWith(Observable.timer(1, TimeUnit.SECONDS, Schedulers.single()))
.subscribe(t -> {
System.out.println("Thread: " + Thread.currentThread());
System.out.println("Value: " + t);
});
System.out.println("After subscribe");
System.out.println("After Thread: " + Thread.currentThread());
// RxJava uses daemon threads, without this, the app would quit immediately
Thread.sleep(3000);
System.out.println("Done");
【讨论】:
main()) 正在运行的主 Thread 中运行 Observer 的操作?