为什么这些代码的输出不同:
Observable.fromArray("Red", "Orange", "Blue")
.doOnNext(color ->{
Log.i(TAG, "Color "+ color + " pushed through on $ " +Thread.currentThread());})
.map(String::length)
.subscribe(length ->
Log.i(TAG, "Length $" + length + " being recieved on $" + Thread.currentThread()));
输出:
Color Red pushed through on $ Thread[main,5,main]
Length $3 being recieved on $Thread[main,5,main]
Color Orange pushed through on $ Thread[main,5,main]
Length $6 being recieved on $Thread[main,5,main]
Color Blue pushed through on $ Thread[main,5,main]
Length $4 being recieved on $Thread[main,5,main]
和
Observable.fromArray("Red", "Orange", "Blue")
.doOnNext(color ->{
Log.i(TAG, "Color "+ color + " pushed through on $ " +Thread.currentThread());})
.map(String::length)
.observeOn(Schedulers.computation())
.subscribe(length ->
Log.i(TAG, "Length $" + length + " being recieved on $" + Thread.currentThread()));
输出:
Color Red pushed through on $ Thread[main,5,main]
Color Orange pushed through on $ Thread[main,5,main]
Color Blue pushed through on $ Thread[main,5,main]
Length $3 being recieved on $Thread[main,5,main]
Length $6 being recieved on $Thread[main,5,main]
Length $4 being recieved on $Thread[main,5,main]
为什么输出的排列不同? 我在observeon方法中使用的每个调度程序,但输出不同 什么时候触发doonnext并订阅?
答案 0 :(得分:1)
doOnNext在当前线程上完成,订阅在Schedulers.computation线程上完成。因此,由于多线程竞争条件,它们完成的顺序可能是随机的。 subscriptionOn仅适用于直接调用的对象。