Reset timeout on event with RxJS

感情迁移 提交于 2019-12-06 04:35:57

Throttle is the typical operator for the delaying with reactive resetting effect you want.

Here's how you can use throttle in combination with scan to gather the combination inputted before the 5 seconds of silence:

var evaluationStream = bothButtons
  .merge(bothButtons.throttle(5000).map(function(){return "reset";})) // (2) and (3)
  .scan(function(acc, x) { // (1)
    if (x === "reset") return "";
    var newAcc = acc + x;
    if (newAcc.length > secretCombination.length) {
      return newAcc.substr(newAcc.length - secretCombination.length);
    }
    else {
      return newAcc;
    }
  })
  .map(function(combination) {
    return combination === secretCombination;  
  });

var wrongStream = evaluationStream
  .throttle(5000)
  .filter(function(result) { return result === false; });

var correctStream = evaluationStream
  .filter(function(result) { return result === true; });

wrongStream.subscribe(function() {
  outputDiv.html("Too slow or wrong!");
});

correctStream.subscribe(function() {
  outputDiv.html("Combination unlocked!");
});

(1) We scan to concatenate the input characters. (2) Throttle waits for 5 seconds of event silence and emits the last event before that silence. In other words, it's similar to delay, except it resets the inner timer when a new event is seen on the source Observable. We need to reset the scan's concatenation (1), so we just map the same throttled Observable to "reset" flags (3), which the scan will interpret as clearing the accumulator (acc).

And here's a JSFiddle.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!