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();
});
}
);
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
.For you specific case, you'd select your delete operations as observables and then forkJoin them.
This is
rxjs@6
syntax. I leaverxjs@5
as an exercise.