Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RxJS - FlatMap observer called multiple times

Tags:

rxjs

I'm trying to understand how flatMap works. I understand that it is a way for handling Observable< Observable < T>>.

Anyhow, I was testing the behaviour of it and got stuck with this:

let plusDom = document.querySelector('#plus');
let minusDom = document.querySelector('#minus');

let minusSource = Rx
              .Observable
              .fromEvent(minusDom, 'click');

let plusSource = Rx.Observable
  .fromEvent(plusDom, 'click');

plusSource
  .flatMap(function(c){
    console.log('Flatmap called');
    return minusSource;
  })
  .subscribe(function(e){
  console.log('done');
})

Here it is the jsbin: https://jsbin.com/sefoyowuqe/edit?html,js,console,output

I don't understand this behaviour:

3 clicks on plusDom prints:
Flatmap called
Flatmap called
Flatmap called

1 click on minusDom prints:

done
done
done

Why when clicking the minusDom it replays the events as many times as we have click the plusDom?

like image 407
kitimenpolku Avatar asked Oct 18 '22 20:10

kitimenpolku


1 Answers

flatMap basically places the returned stream flat into the original stream. What you are probably looking for is switchMap, which will switch to that returned stream and switch to a new stream when the original source emits data by discarding the old one.

When in doubt, switchMap is usually the safest alternative to use.

See the marble-diagrams for comparison:

Flatmap doesn't remove previously "flattened" streams and :

flatMap Marble Diagram

Switchmap removes previously "switched" streams.

switchMap Marble Diagram

like image 91
olsn Avatar answered Oct 21 '22 08:10

olsn