RxScala doOnCompleted在调用.take()后没有触发

时间:2018-04-26 14:22:16

标签: scala observable rx-scala

我是RxScala Observables的新手,在使用take(n)和doOnCompleted()的组合时会遇到奇怪的行为。

下面我有一个测试示例,我认为第一个订阅是正确的(在开始时带有take(2))并输出订阅,下一个,完成和取消订阅方法的所有日志,但是第二个测试(在doOnComplete之后取(2)永远不会到达doOnCompleted方法。

import rx.lang.scala.Observable

object Tester extends App {

    val obs = Observable.from(List(1,2,3,4))

    val obsAddMethodsCorrect = obs.take(2)
        .doOnSubscribe( println("subscribe") )
        .doOnNext( n => println(s"next $n") )
        .doOnError( e => println("error") )
        .doOnCompleted( println("completed") )
        .doOnUnsubscribe( println("unsubscribe") )

    val obsAddMethodsInCorrect = obs
        .doOnError( e => println("error") )
        .doOnCompleted( println("completed") )
        .take(2)
        .doOnNext( n => println(s"next $n") )
        .doOnUnsubscribe( println("unsubscribe") )
        .doOnSubscribe( println("subscribe") )

    obsAddMethodsCorrect.toBlocking.subscribe()
    println("")
    println("The above seems correct. Below seems incorrect")
    println("")
    obsAddMethodsInCorrect.toBlocking.subscribe()

}

以下测试的当前输出。

subscribe
next 1
next 2
completed
unsubscribe

The above seems correct. Below seems incorrect

subscribe
next 1
next 2
unsubscribe

为什么doOnCompleted()在第二个例子中没有被触发?

1 个答案:

答案 0 :(得分:0)

doOnCompleted()运算符将在onCompleted()事件触发时调用其操作。但是,当您在完成发布项目之前取消订阅观察者时,onCompleted()不会被解雇。观察链被有效取消。