【问题标题】:Execute function if and only if a certain amount of time has elapsed since subscription with RxJS当且仅当自使用 RxJS 订阅后经过一定时间时才执行函数
【发布时间】:2018-04-17 09:26:08
【问题描述】:

我正在通过 Observable 进行 API 调用。如果此 API 调用超过 200 毫秒,我想显示一个加载屏幕(通过将 'true' 分配给我的 'loading' 变量),否则我不想显示任何内容,以避免在屏幕上闪烁。

有没有 RxJS 操作符可以做到这一点?

this.apiService.get(`/api/someEndpoint`)

// I hope for something like
.triggerIfAtLeastThisAmountOfTimeHasElapsed(200, () => {
  this.loading = true;
})

.subscribe(response => {

  // Process the response

  this.loading = false;
});

【问题讨论】:

    标签: rxjs rxjs5


    【解决方案1】:

    有很多方法可以做到这一点,因此您可以使用以下方法:

    const api = this.apiService.get(`/api/someEndpoint`);
    const loading = Observable
      .timer(1000)
      .do(() => loading = true) // show loading
      .ignoreElements(); // or `filter(() => false)
    
    Observable.merge(api, loading)
      .take(1)
      .subscribe(() => loading = false);
    

    【讨论】:

    • 如果请求在计时器之前完成,'do'仍然会触发并将加载状态设置为true。
    • 确实如此,所以你可以添加.take(1),然后链会在一次发射后被销毁。
    【解决方案2】:

    与 Martin 的回答相同,这是一个应该模拟您的上下文的示例

    const obs1 = Observable.timer(200).take(1);
    
    const apiSubject = new Subject<string>();
    const apiObs = apiSubject.asObservable();
    const apiExecutionElapsed = 1000;
    
    const obs3 = Observable.merge(obs1, apiObs);
    
    let loading = undefined;
    
    obs3.subscribe(
      data => {
        console.log(data);
        if (loading === undefined && data === 0) {
          loading = true;
        } else {
          loading = false;
        }
        console.log('loading', loading);
      },
      console.error,
      () => {
        loading = false;
        console.log('loading', loading);
      }
    )
    
    setTimeout(() => {
      apiSubject.next('I am the result of the API');
      apiSubject.complete()}, apiExecutionElapsed)
    

    如果 api (apiExecutionElapsed) 的执行时间比配置的计时器长(在这种情况下为 200 毫秒),您会看到 loading 标志先变为真,然后变为假。否则它始终为假。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-12-26
      • 2017-08-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-06-02
      • 1970-01-01
      相关资源
      最近更新 更多