Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to take first occurrence and then supress events for 2 seconds (RxJS)

I think RxJS should perfectly fit to supress dublicate button clicks for 2 seconds. However, Im struggleing with the implementation.

var $button = $('#myButton').button();
$button
    .toObservable("click")
    //.Throttle(2000) // Wouldn't fire the first event instantly :-(
    .Subscribe(function(){ alert('clicked'); }); 

I already created a jsFiddle for your convenience. You need to scroll down in this fiddle, because I just pasted Rx inside as I couldn't find a CDN.

http://jsfiddle.net/cburgdorf/mUMFA/2/

like image 856
Christoph Avatar asked Mar 04 '11 17:03

Christoph


1 Answers

I converted Sergeys answer into JavaScript and think this should be the final way to go.

var $button = $('#myButton').button();
    $button
        .toObservable("click")
        .Take(1)
        .Merge(Rx.Observable.Empty().Delay(2000))
        .Repeat()
        .Subscribe(function(){ console.log('clicked'); }

From my understanding this solutions is actually better because it doesn't rely on a sideeffect which makes it even better in terms of composability.

As Sergey pointed out, you could even go further and implement your own combinator like so:

Rx.Observable.prototype.OneInTime = function(delay){
 return this
        .Take(1)
        .Merge(Rx.Observable.Empty().Delay(delay))
        .Repeat();
};

So our example from above could be reduced to:

var $button = $('#myButton').button();
    $button
        .toObservable("click")
        .OneInTime(2000)
        .Subscribe(function(){ console.log('clicked'); });
like image 126
Christoph Avatar answered Jan 01 '23 08:01

Christoph