Emanuel Ralha
Emanuel Ralha

Reputation: 764

RXjs canceling debounce from source

I'm learning Rx so i dont get quiet well some of the mechanics on Rx, what i want to do i can do it easly with callbacks, but i want to understand Rx.

So what i want to do is, debounce a mouse over event 500ms and show a ui interface, and on mouse out hide that interface, so i have this code:

var outStream = Rx.Observable.fromEventPattern(
          function add (h) {
            asset.events.onInputOut.add(function(){
                h('out');
            });
          }
        );

        var overStream = Rx.Observable.fromEventPattern(
          function add (h) {
            asset.events.onInputOver.add(function(e){
                h('over');
            });
          }
        ).debounce(500);


        var source = Rx.Observable.merge(overStream, outStream);

        source.subscribe(function (x) {
            console.log(x);
          });

What i want is something like this:

.
.mouse over fired after 500ms
.mouseout
.
.mouse over
.mouse out fired before 500ms trigger cancel mouse over

I need some directions, thanks in advance.

Upvotes: 2

Views: 1320

Answers (1)

Matt Burnell
Matt Burnell

Reputation: 2796

I'd use something like this:

var hoverStream = overStream.flatMapLatest(function() {
  return Rx.Observable.timer(500).takeUntil(outStream).map(function() { return 'hover'; })
});

This says "map each overStream element into an observable that will yield a single element after 500ms, but stop listening if outStream yields an element before it arrives". For this to work properly you'll need to remove the debounce from your overStream (and just keep it as a simple stream of all such events).

You could then merge the values into whatever result stream you wanted.

Upvotes: 7

Related Questions