管道内部的Rxjs条件分支路径,然后收敛分支路径



rxjs新手,被条件管道流难住了。

我目前有一个流程,看起来像这个

ngOnInit(): void {
this.myRootService.getRoot().pipe(
map((root: Root) => {
return this.mySecondService.getOtherData(root);
}),
switchMap((otherData: OtherDataType) => {
return this.convertToUsableData(otherData);
})
).subscribe((data: UsableDataType) => {
this.use(data);
});
}

然而,如果我手头已经有了所需的数据,我有机会避免第二次服务呼叫。这将是一个看起来像的流程

ngOnInit(): void {
this.myRootService.getRoot().pipe(
map((root: Root) => {
//we have data already
return this.getUsableData(root);
})
).subscribe((data: UsableDataType) => {
this.use(data);
});
}

我很难弄清楚如何有条件地分支多个管道步骤,然后在以后重新合并。根据我是否有数据,我将在不同阶段处理不同的数据类型。我很希望它的某些部分是有条件的,但我自己对rxjs中条件句的研究让我感到困惑。

当然,我可以只检查this.getUsableData(),然后根据响应将两个独立的流封装在传统的if-else中,但我想知道是否有一种方法可以在管道内智能地完成这一操作。如果我能以某种方式把管道的一部分切掉,我会很高兴的。类似的东西,除了好:

ngOnInit(): void {
this.myRootService.getRoot().pipe(
map((root: Root) => {
return (this.getData(root) || this.mySecondService.getOtherData(root)
.pipe(
map((otherData: OtherDataType) =>
this.convertToData(otherData)
)
));
})
).subscribe((data: UsableDataType) => {
this.use(data);
});
}

如果我理解正确,有时你有数据,所以你不需要订阅额外的可观察对象。但在其他时候,订阅另一个可观察的内容是必要的。

为了实现这一点,当数据已经存在时,您可以使用of()从已经存在的数据中创建一个可观察的数据:

ngOnInit(): void {
this.myRootService.getRoot().pipe(
switchMap(root => {
const existingData = this.getData(root);
return existingData
? of(existingData)
: this.mySecondService.getOtherData(root).pipe(
map(otherData => this.convertToData(otherData))
)
})
).subscribe((data: UsableDataType) => {
this.use(data);
});
}

最新更新