簡體   English   中英

如何延遲發出錯誤的 Observable

[英]How to delay Observable which emits error

假設我有一個函數可以進行 http 調用並返回帶有用戶詳細信息的 Observable。

如果用戶不存在,它會返回發出錯誤的 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));

有什么方法可以延遲發出錯誤的 Observable 嗎?

我很好奇為什么 Observable 在返回錯誤時不會延遲

下面是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());
  }
}

與所有其他操作員一樣, delay訂閱源流 - 在您的情況下為getUser() - 並通知偵聽器。 從源代碼中可以看出,它不會在發生錯誤時安排通知並立即觸發 observable 上的error方法。

在這里您可以了解有關delay運算符的更多信息。

我想延遲對 API 的每個 http 請求,無論它是否成功(以測試響應太長時應用程序的行為方式)

我建議使用 Chrome 調試工具(網絡選項卡)的throttle功能。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM