简体   繁体   中英

RXjs - Continue to listen even after error

I have two (multiple) async functions wrapped in an Observable and want to run them all together and check whenever one has an error or has completed. Here is what I do:

var observables = [];

observables.push(new Observable((observer:any) => {
    async1(options, (error, info) => {
        if (error) {
            observer.error(error);
        } else {
            observer.next(info);
            observer.complete();
        }
    });
}))

observables.push(new Observable((observer:any) => {
    async2(options, (error, info) => {
        if (error) {
            observer.error(error);
        } else {
            observer.next(info);
            observer.complete();
        }
    });
}))

Observable.forkJoin(observables).subscribe(
    data => {
        console.log(data);
    },
    error => {
        console.log(error);
    }
)

Now here is my problem... when both async functions complete successfully, it calls data =>{} and returns both results in an array.

If one of the two functions fails, it will call once error =>{} and that's it. I would like to listen to every error, how can I do that?

The default behaviour for operators combining multiple streams is to exit as soon as one of the stream emits an error notification. This is so because, per Rx grammar, errors are final, so it is generally assumed that the stream returned by the operator must fail eagerly.

One easy solution here is to do away with the error notification and replaces that with an error data structure inserted into a next notification.

So something like :

observables.push(new Observable((observer:any) => {
    async1(options, (error, info) => {
        if (error) {
            observer.next({error});
        } else {
            observer.next({info});
            observer.complete();
        }
    });
}))

Then in your subscribe :

Observable.forkJoin(observables).subscribe(
    arrayData => arrayData.forEach(data => data.info? {
        console.log(data.info);
    } : {
        console.log(data.error);
    })
)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM