Search code examples
javascriptrxjsrxjs5

rxjs infinite loop with an interval variable


I want to make infinite loop with an interval variable using rxjs Observable so I'm trying to rewrite this function in rxjs

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

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

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

I tried

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

but the problem that this is finite to 10 and the interval is constant (getRandomDelayBetween is only called once).

Which operators should I use to produce the same functionality of takeAWalk function?


Solution

  • There are many ways to write this in rxjs, you could try something like this:

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

    Check out the example live here: http://jsbin.com/levakipunu/edit?js,console