- Java 双重比较
- java - 比较器与 Apache BeanComparator
- Objective-C 完成 block 导致额外的方法调用?
- database - RESTful URI 是否应该公开数据库主键?
谁能解释一下为什么 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()
电话 onComplete
而PublishSubject.create()
刚刚创建 Subject
等待调用 onNext()
对他或订户。
所以 Flowable.empty()
是空的,但是 PublishSubject.create()
不是空的。 它不调用onComplete
. 参见 PublishSubject docs了解更多信息。
如果你想要空PublishSubject
, 只需调用 PublishSubject.empty<Boolean>()
.
关于android - PublishSubject 不适用于 firstOrError(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50992991/
谁能解释一下为什么 PublishSubject 不能很好地与 firstOrError() 一起工作? 我希望 firstOrError 在创建没有任何值的 PublishSubject 时返回 N
我是一名优秀的程序员,十分优秀!