Rxjs可观察到等待,直到满足某些条件

dev*_*per 8 javascript observable rxjs typescript angular

我有以下重试逻辑来重试操作.它适用于单个请求.对于多个正在进行的请求,我想在重试之前等待现有的重试逻辑完成.

handleError(errors: Observable<any>) {

    const retryCountStart: number = 1;

    // wait if there is any existing operation retrying
    // once it is complete, continue here

    return errors
        .mergeScan<any, any>(
        (retryCount: any, err: any) => {

            if (retryCount <= 5) {
                return Observable.of(retryCount + 1);
            } 

        },retryCountStart)
        .delay(1000);
}
Run Code Online (Sandbox Code Playgroud)

如何在上述方法中满足某些条件之前添加延迟?

Fai*_*sal 5

您可以使用async/await来实现 Promise 解析:

async handleError(errors: Observable<any>) {

    const retryCountStart: number = 1;

    // wait if there is any existing operation retrying
    // ----------------------------------------------------------
    await new Promise(resolve => {
        // declare some global variable to check in while loop
        while(this.retrying){
            setTimeout(()=> {
                // Just adding some delay 
                // (you can remove this setTimeout block if you want)
            },50);
        }

        // when while-loop breaks, resolve the promise to continue
        resolve();
    });
    // ----------------------------------------------------------

    // once it is complete, continue here

    return errors
        .mergeScan<any, any>(
        (retryCount: any, err: any) => {

            if (retryCount <= 5) {
                return Observable.of(retryCount + 1);
            } 

        },retryCountStart)
        .delay(1000);
}
Run Code Online (Sandbox Code Playgroud)