我已经阅读了有关 blockingSubscribe()
和 subscribe()
的说明,但是既不能编写也找不到一个例子来看这两者的区别。它们似乎都以相同的方式工作。能否有人提供这两个函数的示例,最好用Java。
blockingSubscribe
阻塞当前线程并在其中处理传入的事件。您可以通过运行一些异步源来查看此操作:
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()
)所运行的主线程中执行Observer
的操作吗? - LiTTle