【发布时间】:2018-06-22 17:31:32
【问题描述】:
有人可以解释一下为什么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)
}
【问题讨论】:
-
“测试二”有时间问题。因为您在订阅前使用了
onNext(),所以您不会看到true的值。 -
很公平,你是对的,我会删除那个例子,原因只是误导,我主要关心空场景。另一个呢?
-
在“测试一”中,
publishSubject永远不会完成,因此firstOrError()无法正确决定任何事情。 -
嗯没有多大意义..无论如何,如果是这样的话,实现同样事情的方法是什么?如果不存在则获取第一项或错误?
标签: android rx-java rx-java2 rx-kotlin