Rxjava2阻止订阅与订阅

时间:2019-01-10 11:50:39

标签: java kotlin rx-java2

我已经阅读了有关blockingSubscribe()subscribe()的说明,但我既不能写也找不到示例来了解它们之间的区别。看来这两种方式都是相同的。有人可以提供这两个示例,最好是用Java。

1 个答案:

答案 0 :(得分:4)

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