问题
I have an array of unique ID's and want to perform a bulk action (HTTP patch, delete etc) on them. That needs to be done individually and I need to display individual results.
As the requests are individual and it's responses should not affect each other. Results are displayed as they are received.
Every call is a separate Observable and what I'm looking for is a way to know when all Observables have completed.
The onCompleted
method works only when there are no errors.
The goal is to prevent the button from being clicked while there are still call's being processed.
this.inProgress = {};
this.myIdArray = [1, 2, 3, 4];
actionHandler(type) {
this.inProgress[type] = true;
const myAction = {
patch : id => this.patch(id, this.body),
delete : id => this.delete(id)
};
from(myIdArray)
.pipe (
tap(myAction[type])
)
.subscribe(
res => {},
err => {},
() => this.inProgress[type] = false ); // onCompleted
}
delete(id) {
this.myService.delete(id).subscribe(
res => {} // confirm
err => {} // show error
);
}
回答1:
You can emulate this with forkJoin:
var load = [1, 2, 3, 4].map(id => this.delete(id)); //Observable<T>[]
//do something when each Observable completes
load.forEach(o$ => o$.subscribe(resp => console.log(resp)));
//do something when ALL observables are complete
this.disableButton = true;
forkJoin(load).subscribe(() => this.disableButton = false);//all done!
来源:https://stackoverflow.com/questions/53088099/rxjs-all-individual-observables-completed