【问题标题】:RxJS All Individual Observables completedRxJS 所有单独的 Observables 已完成
【发布时间】:2023-03-30 08:41:01
【问题描述】:

我有一组唯一 ID,并希望对它们执行批量操作(HTTP 补丁、删除等)。这需要单独完成,我需要显示单独的结果。

由于请求是单独的,因此它的响应不应相互影响。结果在收到时显示。

每个调用都是一个单独的 Observable,我正在寻找一种了解所有 Observable 何时完成的方法。 onCompleted 方法仅在没有错误时有效。

目标是防止在仍在处理呼叫时单击按钮。

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

【问题讨论】:

  • 如果你有多个 observables 并且需要等到它们都完成 forkJoin 应该会有所帮助

标签: angular rxjs observable reactive-programming rxjs6


【解决方案1】:

你可以用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!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-17
    • 1970-01-01
    相关资源
    最近更新 更多