简体   繁体   English

如何延迟发出错误的 Observable

[英]How to delay Observable which emits error

Assume I have function which makes http call and returns Observable with user details.假设我有一个函数可以进行 http 调用并返回带有用户详细信息的 Observable。

If user doesn't exist it returns Observable which emits error.如果用户不存在,它会返回发出错误的 Observable。

// 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 ?有什么方法可以延迟发出错误的 Observable 吗?

I'm curious why Observable doesn't delayed if it returns error我很好奇为什么 Observable 在返回错误时不会延迟

Here is the source code of the delay operator:下面是delay运算符的源代码:

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.与所有其他操作员一样, delay订阅源流 - 在您的情况下为getUser() - 并通知侦听器。 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.从源代码中可以看出,它不会在发生错误时安排通知并立即触发 observable 上的error方法。

Here you can learn more about delay operator.在这里您可以了解有关delay运算符的更多信息。

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)我想延迟对 API 的每个 http 请求,无论它是否成功(以测试响应太长时应用程序的行为方式)

I recommend using throttle capabilities of the Chrome Debugging Tools (network tab).我建议使用 Chrome 调试工具(网络选项卡)的throttle功能。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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