gpt4 book ai didi

android - PublishSubject 不适用于 firstOrError()

转载 作者:搜寻专家 更新时间:2023-11-01 08:21:04 27 4
gpt4 key购买 nike

谁能解释一下为什么 PublishSubject 不能很好地与 firstOrError() 一起工作?

我希望 firstOrError 在创建没有任何值的 PublishSubject 时返回 NoSuchElementException

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

@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.

我强调了重要的 fragment 。 Flowable.empty()电话 onCompletePublishSubject.create()刚刚创建 Subject等待调用 onNext()对他或订户。

所以 Flowable.empty()是空的,但是 PublishSubject.create()不是空的。 它不调用onComplete . 参见 PublishSubject docs了解更多信息。

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

关于android - PublishSubject 不适用于 firstOrError(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50992991/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com