RxJava2的blockingSubscribe与subscribe区别

5

我已经阅读了有关 blockingSubscribe() subscribe() 的说明,但是既不能编写也找不到一个例子来看这两者的区别。它们似乎都以相同的方式工作。能否有人提供这两个函数的示例,最好用Java。

1个回答

10

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");

1
那么,它会在当前函数(main())所运行的主线程中执行Observer的操作吗? - LiTTle
@LiTTle,是的,我刚刚检查了一下。 - msangel

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接