【发布时间】:2018-11-19 18:33:17
【问题描述】:
我有以下按预期工作的代码:
const sourceObservable = ... // irrelevant
sourceObservable.subscribe(x => {
doAnyway(x);
if (x.Id) {
doSometing(x);
} else {
// id Not set, get default Id
this.idService.getDefault().subscribe(id => {
x.Id = id;
doSometing(x);
});
}
});
根据this article 嵌套订阅是要避免的。这就是为什么我尝试使用管道重构上面的代码。我尝试使用this Method 实现 if-else 操作,其中过滤用于为每个选项创建一个可观察的分支。最后应该合并订阅。
const obsShared = sourceObservable.pipe(
tap(x => {
doAnyway(x);
}),
share());
const obsIdNotSet = obsShared.pipe(
filter(x => !x.kennzahlId),
merge(x => idService.getDefault().subscribe(id => {
x.Id = id;
// doSomething(x) will nomore be executed here
})));
// even though the true-part is empty I seem to need this to mergeing both options
const obsIdSet = obsShared.pipe(
filter(x => !!x.Id),
tap(() => {
// doSomething(x) will nomore be executed here
}));
obsIdSet.pipe(merge(obsIdNotSet)).subscribe(x => {
// in case obsIdNotSet this will run with x.Id not set because x.Id will be set later
doSometing(x);
});
此代码确实编译和运行没有错误,它只在调用idService.getDefault()..... 之前执行doSomething(x),尽管它会在没有设置x.Id 的情况下被调用。
我做错了什么?
【问题讨论】:
-
查看这篇关于 RxJS 条件工作的整篇文章 blog.strongbrew.io/rxjs-patterns-conditionally-executing-work
标签: angular typescript rxjs