Praveen Prasad
Praveen Prasad

Reputation: 32107

Merge two streams in RxJs without replay

I have stripped down my problem to this simple example.

var button1Click$ = Rx.Observable.fromEvent(document.getElementById('button1'),'click')
                      .map(function(){
                        console.log('Map:all');
                        return "all"
                      })

var odd$ = button1Click$.filter(function(){
   return (Date.now() %2 === 1);
})
.map(function(){
      console.log('Map:odd');
       return "odd"
     })



var combined$ = button1Click$.merge(odd$);
combined$.subscribe(function(ev){
  console.log(ev);
});

Demo: https://jsbin.com/diredeb/edit?js,console,output

I have created a stream of clicks and a stream of odd clicks(based on current time) by filtering clicks stream. Now I want a single stream, which receives both events 'all' and 'odd'. So I am merging these two stream with merge. Problem is with merge, map defined in button1Click$ is getting invoked twice. Suppose If I create another stream named even$ and merge it too, map is getting invoked thrice. Check the demo.

How can I merge the streams so that map (defined for button1Click$) gets invoked only once per click.

Upvotes: 0

Views: 171

Answers (1)

Olaf Horstmann
Olaf Horstmann

Reputation: 16892

Just share the button1Clicked$:

var button1Click$ = Rx.Observable.fromEvent(document.getElementById('button1'),'click')
                  .map(function(){
                    console.log('Map:all');
                    return "all"
                  })
                  .share();

Upvotes: 1

Related Questions