An Observable execution may only have one Observer

André Staltz
InstructorAndré Staltz
Share this video with your friends

Social Share Links

Send Tweet
Published 9 years ago
Updated 6 years ago

Let's remind ourselves of a fundamental behavior of the Observable in RxJS, which is: each Observable execution has only one Observer. This means we cannot directly share one single Observable execution to multiple Observers.

[00:00] Let's remind ourselves of a fundamental behavior of the observable in RxJS. That is, each observable execution has only one observer. For instance, here we have an observable that takes every one second. We have five of those events.

[00:14] Then we have an observer A, which is just an object, which we pass here to subscribe. When we subscribe, we're basically invoking an execution of the observable, using this observer to know where to deliver those events.

[00:30] Let's highlight here that this will actually create an execution of the observable. When we run this, we're going to see events being delivered every second. Now what happens if I want to have multiple observers?

[00:46] When you do something like subscribe again, so now we have observer B, another observer, and we subscribe. We're doing that after two seconds, not at the same time as A did. This will also create its own execution of this observable.

[01:05] As we see here, we see A gets zero, and then B, after two seconds, it gets zero and one. B does not get two here together with A. They don't share the same execution. Fundamentally, we have two executions here running in parallel. They're totally independent to each other.

[01:26] There are cases where you want to have this observing the same events that A did. You can't simply do something like this, like put the observer B, receive the event as well. Here, basically that would mean that when A gets an event, B would also get an event.

[01:48] That's not really what we want, because then, we want B to start after two seconds. Now B is starting at the same time as A is. This is the kind of situation that we solve with the thing called subjects in RxJS. We're going to see, in the following lessons, how to do that, and how to be able to share a single execution with multiple observers.