Multithreading blockingForEach(),为什么要将函数应用于被阻止的观察值
我很难理解阻塞可观测的点,特别是阻塞foreach 将一个函数应用于一个我们永远看不到的可观测对象有什么意义??下面,我尝试按照以下顺序进行控制台输出Multithreading blockingForEach(),为什么要将函数应用于被阻止的观察值,multithreading,rx-java,observable,reactivex,Multithreading,Rx Java,Observable,Reactivex,我很难理解阻塞可观测的点,特别是阻塞foreach 将一个函数应用于一个我们永远看不到的可观测对象有什么意义??下面,我尝试按照以下顺序进行控制台输出 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 我当前的方法在乘法之前打印语句
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
1.一旦不再阻塞,转换后的观测值会发生什么变化?这难道不是不必要的工作,因为我们从来没有看到过这些可见物吗
2.为什么我的系统。扩展。。。当我订阅时出现在我的观察对象之前??它就像Observer2跳过它的阻塞方法,进行System.out调用,然后恢复订阅不清楚您所说的永远不会看到观察者链发出的值是什么意思。观察者链中发射的每个值都会被发射点下游的观察者看到。在订阅观察者链的地方通常是执行副作用的地方,例如打印值或将其存储到变量中。因此,始终可以看到这些值 在您的示例中,您对调度程序的工作方式感到困惑。使用observeOn或subscribeOn运算符时,您是在告诉观察者链在值移动到其他线程后发出值。在线程之间移动数据时,目标线程必须能够处理数据。如果主代码在同一线程上运行,则可以将自己锁定,或者重新排序操作
通常,强烈反对使用阻塞操作。测试时通常可以使用阻塞操作,因为您可以完全控制结果。在其他一些情况下,阻塞可能是有意义的。例如,需要访问数据库或其他资源的应用程序;如果没有该资源,应用程序就没有任何用途,因此它会一直阻塞,直到它可用或出现超时,将其踢出。感谢您的解释。我想我想真正理解的是,如果我们永远无法应用打印、存储等副作用,那么对阻塞的观测值执行某些功能的意义是什么。。。对我来说,这似乎是一种浪费,因为我们永远看不到该函数的结果。例如,在我的示例中,我对阻塞的可观察对象执行system.out调用,blockingForEach中的任何函数似乎都没有意义。我知道观察者看到了这些发射值,但如果我们不采取任何措施,你会误解:副作用确实会发生。有可能是线程死锁阻止了某些东西的运行。很可能您正在尝试从subscribeOn或observeOn操作符尝试使用的同一线程运行observer链。
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 ")
}