我有一个热的可观察的C
,我想听它直到另一个可观察的B
触发(即生成onNext
事件)。 B
是冷的可观察到的,我不想“唤醒”它,直到又有另一个可观察到的A
触发。
换句话说:
C
。A
,当它触发时,我开始听(因此醒来)B
B
触发后,我就停止收听C
这是我的代码:
let b = Observable<Int>.create { s in
print("b got awoken") // I want to see this line only after A fires
s.onNext(666)
s.onCompleted()
return Disposables.create()
}
let c = Observable<Int>.interval(.seconds(1), scheduler: MainScheduler.instance)
c
.takeUntil(b) // I do not want to listen to C after B has fired
.subscribe(onNext: { print("C: \($0)") })
.disposed(by: _bag)
let a = PublishSubject<Int>()
a
.do(onNext:{ print("A: \($0)") })
.flatMap {_ in return b } // After A fires, I "wake up" (or subsribe to) B
.subscribe(onNext:{ print("B: \($0)") })
.disposed(by: _bag)
// Some delay to let C generate some events and listen to them
DispatchQueue.main.asyncAfter(deadline: .now() + 4.0) {
print("anext 1")
a.onNext(1)
}
这是输出:
b got awoken
anext 1
A: 1
b got awoken
B: 666
这是所需的输出:
C: 0
C: 1
C: 2
C: 3
anext 1
A: 1
b got awoken
B: 666
我将如何管理这三个可观察对象以实现所需的行为?
如果我理解这个问题...
func example(a: Observable<Int>, b: @escaping () -> Observable<Int>, c: Observable<Int>) -> Observable<Int> {
return c.takeUntil(a.flatMap { _ in b() })
}