PublishSubject 不适用于 firstOrError()

PublishSubject does not work with firstOrError()

有人可以解释一下为什么 PublishSubject 不能很好地与 firstOrError() 一起使用吗?

我希望 firstOrError 到 return 一个 NoSuchElementExceptionPublishSubject 创建时没有任何值。

为了更好的说明问题,我写了一些测试:

@Test
fun `test one`() {
    // THIS TEST FAILS
    val publishSubject = PublishSubject.create<Boolean>()

    val testSubscriber = publishSubject
        // .toFlowable(BackpressureStrategy.LATEST) // With or without this doesn't make any difference
        .firstOrError()
        .test()

    testSubscriber
        .assertNotComplete()
        .assertError(NoSuchElementException::class.java)
}

@Test
fun `test two`() {
    // THIS TEST PASSES
    val flowable = Flowable.empty<Boolean>()

    val testSubscriber = flowable
        .firstOrError()
        .test()

    testSubscriber
        .assertNotComplete()
        .assertError(NoSuchElementException::class.java)
}

简短版本:Flowable 不发出任何元素并完成,而 PublishSubject 不发出任何元素且不完成

长版:

您假设 PublishSubject.create<Boolean>() 等同于 Flowable.empty<Boolean>()。但他们不是。

首先,让我们看看 firstOrError() 到底做了什么:

Returns a Single that emits only the very first item emitted by this Observable or signals a NoSuchElementException if this Observable is empty.

所以你认为 Flowable.empty<Boolean>() 有效,因为它是空的。 "empty" 是什么意思?

Returns a Flowable that emits no items to the Subscriber and immediately invokes its onComplete method.

我强调了重要的片段。 Flowable.empty() 调用 onCompletePublishSubject.create() 只是创建 Subject 等待调用 onNext() 他或订阅者。

所以Flowable.empty()是空的,但是PublishSubject.create()不是空的。 它不会调用 onComplete 有关详细信息,请参阅 PublishSubject docs

如果你想要空 PublishSubject,只需调用 PublishSubject.empty<Boolean>()