Search code examples
javascripteventsreactive-extensions-js

Buffer/Ignore events until period of inactivity then fire only last event


I have an observable that when it fires a message is displayed. After a delay I want to fade that message out, unless in the mean time that observable has fired again.

In other words given an observable, I want to create another observable, such that when the last event fired the first observable is more than a specified time ago the created observable fires that last event.


Solution

  • Given the observable o, the following code does what I want:

    var d = o
        .DistinctUntilChanged()
        .Timestamp()
        .Select(function(e) { return e.Timestamp; })
        .Publish();
    d.CombineLatest(d.Delay(2000), function(a, b) { return a === b; })
        .Where(function(o) { return o; })
        .Subscribe(function(v) { /* ... do something with v ... */ });
    d.Connect();
    

    This creates an observable d that will fire after 2000ms of inactivity from o.

    NOTE: The value of v in the subscribing function is always true.