cgross cgross - 2 months ago 9
Javascript Question

RxJS multiple subscriptions to Observable?

I create my own observable and subscribed two functions to it. I would expect to have both functions executed for each element in the sequence but only the last one is.

let observer = null
const notificationArrayStream = Rx.Observable.create(function (obs) {
observer = obs;
return () => {}
})

function trigger(something) {
observer.next(something)
}

notificationArrayStream.subscribe((x) => console.log('a: ' + x))
notificationArrayStream.subscribe((x) => console.log('b: ' + x))

trigger('TEST')


Expected output

a: TEST
b: TEST


Actual output

b: TEST


Here's the JSBin: http://jsbin.com/cahoyey/edit?js,console

Why is that? How can I have multiple functions subscribe to a single Observable?

Answer

To have multiple functions subscribe to a single Observable, just subscribe them to that observable, it is that simple. And actually that's what you did.

BUT your code does not work because after notificationArrayStream.subscribe((x) => console.log('b: ' + x)) is executed, observer is (x) => console.log('b: ' + x)), so observer.next will give you b: TEST.

So basically it is your observable creation which is wrong. In create you are passed an observer as parameter so you can pass it values. Those values you need to generate somehow through your own logic, but as you can see your logic here is erroneous. I would recommend you use a subject if you want to push values to the observer.

Something like:

const notificationArrayStream = Rx.Observable.create(function (obs) {
  mySubject.subscribe(obs);
  return () => {}
})

function trigger(something) {
  mySubject.next(something)
}
Comments