Ortal Blumenfeld Lagziel
Ortal Blumenfeld Lagziel

Reputation: 2555

How can I combine 2 observable that return success result event if one of them was failed?

I want to subscribe to two observables methods but one might get an error and the second may success. But when I try to do it I get only error event if one of them return success

when I'm using combineLatest I get only error even if the first is success

 combineLatest(
    this.createTable1(),
      this.createTable2()
     ).pipe(untilDestroyed(this))
      .subscribe(() => {
        alert('suceess');
      }, (error) => {
        alert('error');
      });

when I do like the following it works only if the second is failed, if the first is failed I didn't get an alert of success:

   this.createTable1().pipe(untilDestroyed(this)).subscribe( () => {
      alert('1suceess');
         this.createTable2().pipe(untilDestroyed(this)).subscribe( () => {
           alert('2suceess');
         }, () => {
           alert('error');
         });
      }, () => {
      alert('error');
    });

How can I fix it?

Upvotes: 1

Views: 312

Answers (1)

David G.
David G.

Reputation: 1485

I think your problem is RxJS completes the stream once an error has been caught before you get the value for the other one, so you need to handle the errors in each stream and make them back into an observable.

combineLatest(
  this.createTable1().pipe(catchError(() => of('Errored'))),
  this.createTable2().pipe(catchError(() => of('Errored')))
).pipe(untilDestroyed(this))
 .subscribe(() => {
   alert('suceess');
 }, (error) => {
   alert('error');
 });

This should work. I didn't know this myself, I tested it in this StackBlitz: https://stackblitz.com/edit/rxjs-xzdtpn?devtoolsheight=60&file=index.ts

You'll see if you comment out line 9, we never get to know about the later observable.

EDIT: I am adding a different version in case you don't care to know if one of the observables failed:

merge(
  this.createTable1().pipe(catchError(() => EMPTY)),
  this.createTable2().pipe(catchError(() => EMPTY))
).pipe(untilDestroyed(this))
 .subscribe(() => {
   alert('suceess');
 }, (error) => {
   alert('error');
 });

Upvotes: 2

Related Questions