【问题标题】:rxjs infinite loop with an interval variable带有间隔变量的rxjs无限循环
【发布时间】:2016-12-17 10:41:50
【问题描述】:

我想使用 rxjs Observable 使用区间变量创建无限循环 所以我试图在 rxjs 中重写这个函数

takeAWalk(player){
    setTimeout(() => {

      console.log("Player is walking...");

      takeAWalk(player);
    }, getRandomDelayBetween(1000, 2500));
}

我试过了

Observable
  .timer(0, getRandomDelayBetween(1000, 2500))
  .take(10)
  .timeInterval()
  .subscribe(res=>{
    console.log("player is walking ...");
  });

但问题是有限到 10 并且间隔是恒定的(getRandomDelayBetween 只被调用一次)。

我应该使用哪些运算符来产生与takeAWalk 函数相同的功能?

【问题讨论】:

    标签: javascript rxjs rxjs5


    【解决方案1】:

    rxjs 有很多种写法,你可以试试这样的:

    Rx.Observable.of(null)
      .concatMap(() => Rx.Observable.timer(Math.random() * 1500))
      .do(() => console.log("player is walking ..."))
      .repeat()  // optionally .repeat(10)
      .subscribe();
    

    在此处查看示例:http://jsbin.com/levakipunu/edit?js,console

    【讨论】:

      【解决方案2】:

      只是为了扩展expand :')

      这是我创建的一个 runWhile 函数,它的作用类似于一个 while 循环,带有一个奖励间隔值,用于延迟每个循环之间的事件。

      在条件为假之前,它不会继续循环。

      import { EMPTY, Observable, of, OperatorFunction } from 'rxjs';
      import { delay, expand, filter, flatMap, mapTo } from 'rxjs/operators';
      
      /**
       * Like a while loop for RxJS,
       * while (condition()) { doFn() }
       *
       * @param condition
       * @param doFn
       * @param interval
       * @param initialValue
       */
      export function runWhile<T = any> (
        condition : () => boolean,
        doFn : () => Observable<T>,
        interval = 0,
        initialValue = null,
      ) : OperatorFunction<T, T> {
        return flatMap<T, T>((initial) => {
          return of(condition())
            .pipe(
              expand((cond) => {
                if (cond === false) {
                  return EMPTY;
                }
      
                return doFn().pipe(delay(interval), mapTo(condition()));
              }),
              filter(cond => cond === false),
              mapTo(initial),
            );
        });
      }
      

      有关其工作原理的示例,请参阅此 codepen。 CodePen

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-04-07
        • 1970-01-01
        • 2018-10-29
        • 2021-02-15
        • 1970-01-01
        • 2020-10-31
        • 2021-04-29
        • 1970-01-01
        相关资源
        最近更新 更多