Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

rxjs map operator evaluated for each subscriber

Why is the map operator evaluated for each subscriber instead of once?

const obs1 = Rx.Observable.interval(1000).take(1).map((x, i) => {
  console.log(i+1 + ':1 map')
  return 'obs1';
})

const obs2 = Rx.Observable.interval(1300).take(1).map((x, i) => {
  console.log(i+1 + ':2 map')
  return 'obs2';
})

const obs3 = Rx.Observable.interval(1700).take(2).map((x, i) => {
  console.log(i+1 + ':3 map')
  return 'obs3';
})

const view = obs1.combineLatest(obs2, obs3, (obs1, obs2, obs3) => {                 return obs1 + ', ' + obs2 + ', ' + obs3; });

// Every subscriber adds more calls to map - why is it called multiple     times at the same time ?

view.subscribe((value) => {
  console.log('sub1: ' + value)
});

view.subscribe((value) => {
  console.log('sub2: ' + value)
});

view.subscribe((value) => {
  console.log('sub3: ' + value)
});

I created a testcase here: http://jsbin.com/jubinuf/3/edit?js,console

Can I write this testcase differently to avoid this behaviour?

like image 899
kask Avatar asked Jan 21 '16 19:01

kask


People also ask

Does map return an observable?

get(apiURL) returns an Observable . map is an observable operator which calls a function for each item on its input stream and pushes the result of the function to its output stream. In this case each input item is a Response object.

What is RxJS map operator?

RxJS map() operator is a transformation operator used to transform the items emitted by an Observable by applying a function to each item. It applies a given project function to each value emitted by the source Observable and then emits the resulting values as an Observable.

What is the purpose of the observable map operator?

The Map operator applies a function of your choosing to each item emitted by the source Observable, and returns an Observable that emits the results of these function applications.

Do vs map RxJS?

do() is to execute code for each event. A difference to . map() is, that the return value of . do() is ignored and doesn't change what value the subscriber receives.


1 Answers

Every subscriber will run through the Observable sequence. If you want everyone to get the resulting stream instead, use .publish().refCount().

http://jsbin.com/ditikonopi/edit?js,console

The .publish() will return an observable sequence that shares a single subscription to the underlying sequence. refCount() will stay connected to the source so long as there is at least one subscription.

like image 126
Kyle Kelley Avatar answered Nov 09 '22 23:11

Kyle Kelley