多个订阅完成/拆卸后如何执行操作

时间:2019-09-20 08:30:52

标签: angular typescript rxjs

我正在创建一种离子清新剂。我有一个执行多个get请求的组件。他们每个人都有自己的方法。我要实现的是,我想在完成所有订阅后执行event.target.complete()。以下是我尝试执行的操作:

private _dataFromOne;
private _dataFromTwo;

ngOnInIt() {
    this.getAllData();
}

/*This method will be called from HTML as well with $event*/
private getAllData(event = null) {
    if ($event) {
          // So if it was only one method, then this would work
        this.methodOne().add(() => {
            event.target.complete()  // teardown logic. End when _subOne is unsubscribed
        });
        // This is where I'm confused. How do I do it when subscription from both method is unsubscribed?
        // this.methodTwo();
    } else {
        this.methodOne();
        this.methodTwo();
    }
}

private methodOne() {
    return this.doGetRequest.get().subscribe((data) => {
        this._dataFromOne = data;
    });
}

private methodTwo() {
    return this.doSomeGetRequest.get().subscribe((data) => {
        this._dataFromTwo = data;
    });
}

任何帮助我指出正确方向的方法将不胜感激。谢谢。

2 个答案:

答案 0 :(得分:2)

您可以尝试从2种方法中返回Observable并将它们合并为一种:

private getAllData(event = null) {
    merge(
        this.methodOne(),
        this.methodTwo()
    ).pipe(
        finalize(() => {
            if (event) {
                event.target.complete();
            }
        }),
    ).subscribe();
}


private methodOne() {
    return this.doGetRequest.get().pipe(tap(data => {
        this._dataFromOne = data;
    }));
}

private methodTwo() {
    return this.doSomeGetRequest.get().pipe(tap(data => {
        this._dataFromTwo = data;
    }));
}

或没有tap(订阅之外的副作用):

private getAllData(event = null) {
    forkJoin(
        this.methodOne(),
        this.methodTwo()
    ).subscribe(([data1, data2]) => {
        this._dataFromOne = data1;
        this._dataFromTwo = data2;
    }, err => {
        //what do you do if one of them fails?
    }, () => {
        if (event) {
            event.target.complete();
        }
    });
}


private methodOne() {
    return this.doGetRequest.get1();
}

private methodTwo() {
    return this.doSomeGetRequest.get2();
}

答案 1 :(得分:1)

您可以将Observable封装在一个函数中,该函数可在获取结果后解析Promise,将所有Promises堆叠到Promise数组中并使用Promise.All()