RxJS All Individual Observables completed

杀马特。学长 韩版系。学妹 提交于 2021-01-29 08:02:09

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!