Guarantee observable subscription finishes before

2019-09-21 08:59发布

问题:

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();
        });
    }
);

回答1:

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.