简体   繁体   中英

How to delay Observable which emits error

Assume I have function which makes http call and returns Observable with user details.

If user doesn't exist it returns Observable which emits error.

// Get user by id
function getUser(id) {
  return Rx.Observable.create(obs => {
    if (id === 1) {
      obs.next('200 - User found');
      obs.complete();
    } else {
      obs.error('404 - User not found');
    }
  });
}

// This will print "200 - User found" in the console after 2 seconds
getUser(1)
  .delay(2000)
  .subscribe(r => console.log(r));

// !!! Delay will not work here because error emmited
getUser(2)
  .delay(2000)
  .subscribe(null, e => console.log(e));

Is there any way to delay Observable which emits error ?

I'm curious why Observable doesn't delayed if it returns error

Here is the source code of the delay operator:

class DelaySubscriber<T> extends Subscriber<T> {
  ...

  protected _next(value: T) {
    this.scheduleNotification(Notification.createNext(value)); <-------- notification is scheduled
  }

  protected _error(err: any) {
    this.errored = true;
    this.queue = [];
    this.destination.error(err); <-------- error is triggered immediately
  }

  protected _complete() {
    this.scheduleNotification(Notification.createComplete());
  }
}

Just as with every other operator, delay subscribes to the source stream - getUser() in your case - and notifies the listener. You can see from the source code that it doesn't schedule notification when an error occurs and trigger the error method on the observable immediately.

Here you can learn more about delay operator.

I want to delay every http request to the API regardless success it or not (to test how app will behave if response is too long)

I recommend using throttle capabilities of the Chrome Debugging Tools (network tab).

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