我很难理解可观察到的阻塞点,特别是blockingForEach()
把一个函数应用到一个我们永远不会看到的可观察到的地方,有什么意义?下面,我试图按照以下顺序输出控制台
this is the integer multiplied by two:2
this is the integer multiplied by two:4
this is the integer multiplied by two:6
Statement comes after multiplication我的当前方法在乘法之前打印语句。
fun rxTest(){
val observer1 = Observable.just(1,2,3).observeOn(AndroidSchedulers.mainThread())
val observer2 = observer1.map { response -> response * 2 }
observer2
.observeOn(AndroidSchedulers.mainThread())
.subscribeOn(AndroidSchedulers.mainThread())
.subscribe{ it -> System.out.println("this is the integer multiplie by two:" + it) }
System.out.println("Statement comes after multiplication ")
}现在,我已经将我的方法更改为包含blockingForEach()
fun rxTest(){
val observer1 = Observable.just(1,2,3).observeOn(AndroidSchedulers.mainThread())
val observer2 = observer1.map { response -> response * 2 }
observer2
.observeOn(AndroidSchedulers.mainThread())
.subscribeOn(AndroidSchedulers.mainThread())
.blockingForEach { it -> System.out.println("this is the integer multiplie by two:" + it) }
System.out.println("Statement comes after multiplication ")
}1.转化后的可观测值一旦不再阻塞,会发生什么情况?这难道不是不必要的工作,因为我们从来没有看到那些可观察的?
2.)为什么我的System.out (“语句.”)出现在我订阅时出现在我的可观测值前面??它就像observable2跳过它的阻塞方法,进行System.out调用,然后恢复它的订阅
发布于 2018-06-21 21:05:18
不清楚你所说的“永远看不到”观察者链发出的值是什么意思。观察者链中发出的每个值都由从其发出点下游的观察者看到。订阅观察者链的地方通常是执行副作用的地方,例如打印值或将值存储到变量中。因此,这些值总是可见的。
在您的示例中,您会对调度程序的工作方式感到困惑。当您使用observeOn()或subscribeOn()运算符时,您正在告诉观察者链在将该值转移到另一个线程后发出值。在线程之间移动数据时,目标线程必须能够处理数据。如果您的主代码运行在同一个线程上,您可以将自己锁在外部,否则将重新排序操作。
通常,对阻塞操作的使用是非常不鼓励的。阻塞操作通常可以在测试时使用,因为您可以完全控制结果。还有其他几种情况,阻塞可能是有意义的。例如,需要访问数据库或其他资源的应用程序;如果没有该资源,应用程序就没有用途,因此它会阻塞,直到可用或超时,并将其踢出。
https://stackoverflow.com/questions/50975999
复制相似问题