Stopping a shared observable execution

Share this video with your friends

Send Tweet

ConnectableObservable has the connect() method to conveniently dictate the start of the shared execution of the source Observable. However, we need a mechanism to dictate the stop of the shared execution, otherwise a leak happens. This lesson will teach you how to do that, and it's all about Subscriptions.

Tomasz Kula
Tomasz Kula
~ 8 years ago

Does calling unsubscribe on connectableObservable subscription clear subscriptions for subA and subB?

Asumming:

  • sub = connectableObservable subscription to internal Subject
  • subA = obsA subscription to connectableObservable
  • subB = obsB subscription to connectableObservable

What should correct usubscribe code look like? ###A

setTimeout(() => {
  subA.unsubscribe();
  subB.unsubscribe();
  sub.unsubscribe();
}, 5000)

###B

setTimeout(() => {
  sub.unsubscribe();
}, 5000)
André Staltz
André Staltz(instructor)
~ 8 years ago

Hi Tomasz. Unsubscribing from sub will not clear subscriptions A and B, because those are attached to the underlying subject. The subscription sub is attached to the source observable. So you would have to write:

setTimeout(() => {
  subA.unsubscribe();
  subB.unsubscribe();
  sub.unsubscribe();
}, 5000)

That said, usually we don't explicitly call connect(), so this use case is actually rather rare. As we see later on in the course, there are better ways of using multicast so that subscriptions are handled more automatically.