Most of the time I am able to avoid nested subscriptions but I'm not sure how to do it with this code:
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);
});
Ideally I want to have all side effects either in a tap() or in a single non-nested subscribe(), how do I do this?
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);
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.