【问题标题】:RxJS wait until desired value with timeoutRxJS 等到所需的值并超时
【发布时间】:2021-06-24 13:24:04
【问题描述】:

我正在使用 RxJS 6.6.0

假设我有一个初始值 false 的布尔 observable。

value$: Observable<boolean>;

我想等到当点击按钮时这个 observable 变为 true,超时时间为 2 秒。

这是我的代码:

async onButtonClick(): Promise<void> {
    const isTrue = await this.value$.pipe(
          filter(e => e == true),
          // if it's not true after 2 seconds, return false!
        ).toPromise();

    if (isTrue) {
      console.log('Success')
    }
}

如何使用 RxJS 实现这一点?

【问题讨论】:

    标签: typescript rxjs


    【解决方案1】:

    您可以为此使用timeoutWith(),并且您可能还需要take(1) 来完成链,以便toPromise() 知道何时解决(以防value$ 无法自行完成)。

    const isTrue = await this.value$.pipe(
      filter(e => e),
      timeoutWith(2000, of(false)),
      take(1),
    ).toPromise();
    

    【讨论】:

      【解决方案2】:

      也许是为了避免 Promise 这样做:

        this.value$.pipe(
          filter(Boolean),
          debounceTime(2000),
          take(1) // if you want to complete an Observable after first true emission
       ).subscribe(
           () => console.log('Success')
       );
      

      filter(Boolean) 将防止错误值发射,并且只会发射通过提供条件的值,在您的情况下为真。

      debounceTime 延迟源发出的值。

      take(1) 仅发出源 Observable 发出的第一个计数值。通常这是在管道链中调用的最后一个函数是一件好事

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2022-08-18
        • 1970-01-01
        • 2017-03-16
        • 1970-01-01
        • 2019-08-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多