gpt4 book ai didi

rxjs - 多个订阅嵌套在一个订阅中

转载 作者:行者123 更新时间:2023-12-04 13:17:51 28 4
gpt4 key购买 nike

我发现自己在尝试设置一个非常简单的 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
});

});

我知道嵌套订阅不是好习惯,我尝试使用 flatMapconcatMap但并没有真正了解如何实现这一点。

最佳答案

您可以使用 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();

这样, secondthird正在异步运行 first发出。

关于rxjs - 多个订阅嵌套在一个订阅中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58414661/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com