3

If I return a BehaviorSubject as an Observable from a service and subscribe to that Observable in a component and then call either take(1) or unsubscribe, does the BehaviorSubject keep emitting values? Is it effected?

Edit Thank you everyone for the responses. That clears things up for me.

cyberguy
  • 233
  • 3
  • 10
  • 1
    If you use take(1) the first emitted value will be used and no more. I mean if you emit more values they will be emitted but the part where you use take(1) will only enter into the subscribe for once that too with the first emitted value. – Ramesh Reddy Jan 09 '20 at 17:12
  • 1
    What have you tried to test this? Have you connected to the observable from a BehaviorSubject in multiple components, sent values to that subject after unsubscribing and seeing the effects in the components still subscribed? – Alexander Staroselsky Jan 09 '20 at 17:12
  • 1
    Yes, it does. Simple experiment: https://stackblitz.com/edit/rxjs-x8q4ee?devtoolsheight=60. A Subject is a hot, multicast observable, so you can subscribe multiple times, and the events will be multicast to every observed. Unsubscribing one oberver doesn't affect the others. – JB Nizet Jan 09 '20 at 17:14

2 Answers2

3

Observables (which are actually just the factories for observable streams) are in general not affected by their subscribers. However, they CAN be implemented in a way that unsubscribing to them affects other subscribers. This is not the case for BehaviorSubject though.

Generally, you wouldn't want to alter other streams when a subscriber unsubscribes. This would go against the elasticity and reciliency goals of reactive programming (shared state potentially creates bottlenecks and leads to errors being propagated to other streams)

So yes, BehaviorSubject will keep emitting to other subscribers as long as it's not completed. It won't, however, emit to the take(1) subscriber at any time after it has sent the first notification.

ggradnig
  • 13,119
  • 2
  • 37
  • 61
0

In this scenarios there are two different roles: The Observable and the Observer (the one who subscribes to the Observable). Actions taken by the Observer don't affect the behaviour of the Observable, therefore if an Observer unsubscribe to an Observable it does not affect the Observable itself. Other Observers to that Observable continue to be subscribed and the Observable continues to emit values.

Cindy Meister
  • 25,071
  • 21
  • 34
  • 43