如何避免具有逻辑和副作用的嵌套订阅
How to avoid nested subscription with logic and side effects
大多数时候我可以避免嵌套订阅,但我不确定如何使用此代码来做到这一点:
const appleStuff = obtainAppleStuff();
// observeAll returns Observable<Apple[]>
appleService.observeAll().subscribe(apples => {
let apple = apples.find(this.appleFilter);
if(!apple){
apple = appleService.create();
apple.type = "Red";
apple.size = 5;
appleService.update(apple);
if(apples.length !== 0){
this.appleService.observeWormsOfApple(apples[0]).subscribe(worms => {
appleService.linkWorms(worms, apple);
});
}
}
this.linkAppleStuff(appleStuff, apple);
});
理想情况下,我希望在 tap() 或单个非嵌套 subscribe() 中产生所有副作用,我该怎么做?
const appleStuff = obtainAppleStuff();
appleService
.observeAll()
.pipe(
map(apples => {
let apple = apples.find(this.appleFilter);
if (!apple) {
apple = appleService.create();
apple.type = "Red";
apple.size = 5;
}
return [apples, apple];
}),
tap(([, apple]) => {
appleService.update(apple);
this.linkAppleStuff(appleStuff, apple);
}),
filter(([apples]) => !!apples.length),
switchMap(([apples, apple]) => this.appleService.observeWormsOfApple(apples[0]).pipe(withLatestFrom([apple])))
)
.subscribe(([worms, apple]) => {
appleService.linkWorms(worms, apple);
});
大多数时候我可以避免嵌套订阅,但我不确定如何使用此代码来做到这一点:
const appleStuff = obtainAppleStuff();
// observeAll returns Observable<Apple[]>
appleService.observeAll().subscribe(apples => {
let apple = apples.find(this.appleFilter);
if(!apple){
apple = appleService.create();
apple.type = "Red";
apple.size = 5;
appleService.update(apple);
if(apples.length !== 0){
this.appleService.observeWormsOfApple(apples[0]).subscribe(worms => {
appleService.linkWorms(worms, apple);
});
}
}
this.linkAppleStuff(appleStuff, apple);
});
理想情况下,我希望在 tap() 或单个非嵌套 subscribe() 中产生所有副作用,我该怎么做?
const appleStuff = obtainAppleStuff();
appleService
.observeAll()
.pipe(
map(apples => {
let apple = apples.find(this.appleFilter);
if (!apple) {
apple = appleService.create();
apple.type = "Red";
apple.size = 5;
}
return [apples, apple];
}),
tap(([, apple]) => {
appleService.update(apple);
this.linkAppleStuff(appleStuff, apple);
}),
filter(([apples]) => !!apples.length),
switchMap(([apples, apple]) => this.appleService.observeWormsOfApple(apples[0]).pipe(withLatestFrom([apple])))
)
.subscribe(([worms, apple]) => {
appleService.linkWorms(worms, apple);
});