RxJava 棘手的 startWith(Observable) [英] RxJava tricky startWith(Observable)
问题描述
以下代码仅在 observable2 完成后才从 observable1 发出项目.
The following code emits items from observable1 only after observable2 is completed.
observable1.startWith(observable2)
.subscribe()
我需要实现另一种行为
observable1 -> 0 1 2 3
observable2 -> 1 2 3 4 5 6
observable1.startWithDefault(observable2)
-> 1 2 0 1 2 3
第二个 observable 仅在第一个 observable 为空时才发出项目,然后从第一个 observable 发出项目.
The second observable emits items only while first observable is empty and then items from first one are emited.
我无法仅使用基本运算符找到正确的解决方案,自定义运算符 startWithDefault 的正确 RxJava 2 实现应该是什么样的?
I could not find correct solution using only basic operators, what is correct RxJava 2 implementation of custom operator startWithDefault should look like?
附言
observable1.subscribe()
observable2.takeUntil(observable1).subscribe()
不是正确的解决方案,因为在从 observable1 立即发射的情况下发生竞争
is not correct solution because of race in case of immediate emit from observable1
推荐答案
方向很好,但是你需要 publish(Function)
来分享 observable1
的信号和concatEager
在切换时不会丢失元素:
The direction was good, but you need publish(Function)
to share observable1
's signals and concatEager
to not lose elements from it when the switch appens:
observable1.publish(o ->
Observable.concatEager(observable2.takeUntil(o), o)
)
.subscribe(...)
这篇关于RxJava 棘手的 startWith(Observable)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!