Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I am doing a bit of a cascade delete with multiple service calls. Some of the later subscriptions rely on previous subscriptions to finish. How can I guarantee an subscription finishes before moving onto my next code?

// Need to make sure this code completes
data.forEach(element => {
    this.myService.delete(element.id).subscribe();
});

// Before running this code
this.myService.getAll().subscribe(res => {
        res.data.forEach(element => {
            this.myService.delete(element.id).subscribe();
        });
    }
);
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
223 views
Welcome To Ask or Share your Answers For Others

1 Answer

A Subscription has a singular purposes: disposing, but you have options:

  • If you want to subscribe to observables one after another, you can use concat.

  • If you want to subscribe to multiple observables at the same time and combine the last value of each, you can use forkJoin.

  • If you want to use yielded value of an observable in another observable, you can use flatMap.


import { forkJoin, interval, concat, of } from "rxjs";
import { first, flatMap } from "rxjs/operators";

var combinedIntervals =
    forkJoin(
        interval(1000).pipe(first()),
        interval(2500).pipe(first())
    ).pipe(
        flatMap(([a, b]) => of(`${a} and ${b}`))
    );

concat(
    combinedIntervals,
    of("after both intervals")
)
.subscribe(
    console.log.bind(console)
);


// 0 and 0
// after both intervals

For you specific case, you'd select your delete operations as observables and then forkJoin them.

var data = [];

var obsBatch1 = data.map(element => myService.delete(element.id));
var obsBatch2 =
    forkJoin(
        obsBatch1,
        elements => elements.map(
            element => myService.delete(element.id)
        )
    );

obsBatch2.subscribe();

This is rxjs@6 syntax. I leave rxjs@5 as an exercise.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...