简体   繁体   English

Rxjava2 blockingSubscribe vs subscribe

[英]Rxjava2 blockingSubscribe vs subscribe

I have read the explanation about blockingSubscribe() and subscribe() but neither I can write nor find an example to see the difference of these. 我已经阅读了有关blockingSubscribe()subscribe()的解释,但我既不能编写也不能找到一个示例来查看这些的区别。 It seems that both of these work the same way. 似乎这两种方式都是一样的。 Could someone provide an example of these 2, preferably in Java. 有人可以提供这些2的示例,最好是Java。

blockingSubscribe blocks the current thread and processes the incomnig events on there. blockingSubscribe阻塞当前线程并处理那里的incomnig事件。 You can see this by running some async source: 你可以通过运行一些异步源来看到这个:

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 gives no such confinement and may run on arbitrary threads: 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");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM