我发现尝试设置一个非常简单的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
运算符进行操作。
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();
这样,一切都按照定义的顺序链接和执行。
您可以执行以下操作:
subject$: Subject<any> = new Subject();
this.subject$.pipe(
switchMap(() => subject0),
tap(a => {
this.a = a;
}),
switchMap(() => subject1),
tap(x => {
// Do some stuff that require this.a to exists
}),
switchMap(() => subject2),
tap(y => {
// Do some stuff that require this.a to exists
})
);
如果要触发此操作,只需调用this.subject $ .next();
编辑:这是使用forkJoin的可能方法
subject$: Subject<any> = new Subject();
this.subject$.pipe(
switchMap(() => subject0),
tap(a => {
this.a = a;
}),
switchMap(
() => forkJoin(
subject1,
subject2
)),
tap([x,y] => {
// Do some stuff that require this.a to exists
})
);