我发现自己在尝试设置一个非常简单的 rxjs 订阅流时感到困惑。将多个不相关的订阅嵌套到另一个订阅中。
我在一个有角度的应用程序中,在进行其他订阅之前,我需要一个主题来填充下一个。
这将是我想要实现的嵌套版本。
subject0.subscribe(a => {
this.a = a;
subject1.subscribe(x => {
// Do some stuff that require this.a to exists
});
subject2.subscribe(y => {
// Do some stuff that require this.a to exists
});
});
我知道嵌套订阅不是好习惯,我尝试使用
flatMap
或 concatMap
但并没有真正了解如何实现这一点。
最佳答案
您可以使用 concat
来做到这一点。运算符(operator)。
const first = of('first').pipe(tap((value) => { /* doSomething */ }));
const second = of('second').pipe(tap((value) => { /* doSomething */ }));
const third = of('third').pipe(tap((value) => { /* doSomething */ }));
concat(first, second, third).subscribe();
这样,一切都按照定义的顺序链接和执行。
编辑
const first = of('first').pipe(tap(value => {
// doSomething
combineLatest(second, third).subscribe();
}));
const second = of('second').pipe(tap(value => { /* doSomething */ }));
const third = of('third').pipe(tap(value => { /* doSomething */ }));
first.subscribe();
这样,
second
和 third
正在异步运行 first
发出。
关于rxjs - 多个订阅嵌套在一个订阅中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58414661/