【发布时间】:2019-07-24 14:28:23
【问题描述】:
我有两个函数,一个返回observableA,一个返回observableB。我希望 getter 以及 observableB 的订阅延迟到 observableA 完成(但当我订阅 observableB,observableA 已经完成时,也可能是这种情况)。
我已经尝试使用pipe 和skipUntil,但不幸的是,如果observableA 尚未完成,这只会阻止执行并且不会延迟它。
functionA() {
this.observableA$ = getObservableA()
this.observableA$.subscribe(_ => {
// A: This line should execute *before* line B
})
}
functionB() {
this.observableB$ = getObservableB() // This getter should execute *after* line A
this.observableB$.subscribe(_ => {
// B: This line should execute *after* line A
})
}
// Two functions are called independently
functionA()
functionB()
如果能找到一种非常 RxJS-ish 的方式会很棒:)
更新 1:concat 的问题:
如前所述,这两个函数都是独立调用的,这将导致在使用concat 时重复执行observableA$,就像建议的那样。 functionB 中的订阅也会执行两次我不想要的。
functionA() {
this.observableA$ = getObservableA()
this.observableA$.subscribe(_ => {
// A: This line should execute *before* line B
})
}
functionB() {
Observable.concat(
this.observableA$, // I get executed once again :(
Observable.defer(() => getObservableB()) // To prevent earlier execution
).subscribe(() => {
// B: This line should execute *after* line A
console.log("I'm logged twice, once for each observable :(")
})
}
// Two functions are called independently
functionA()
functionB()
更新 2:@Wilhelm Olejnik 通过使用额外的 BehaviorSubject 解决了这个问题
【问题讨论】:
-
查看 concat 或 concatMap 运算符。
-
我已经用一个例子更新了我的答案,为什么
concat不起作用。 (或者至少不适用于我的使用方式。)
标签: angular typescript rxjs reactive-programming