Mahesh V S
Mahesh V S

Reputation: 582

Is it safe to assume that the RxJS will trigger the next of each observer in the subscription order?

Is it safe to assume that RxJS will trigger the next function of each of its observers in the order they have subscribed. I have a class with a public propery of BehaviorSubject. The first subscription made to it will be from with in the class' constructor. I would like to make sure that the next of this private subscription works before any other's.

Upvotes: 2

Views: 278

Answers (2)

Matt Burnell
Matt Burnell

Reputation: 2796

Practically speaking, yes, this is safe; the implementation of the Subject class (from which BehaviorSubject inherits) always processes subscriptions in the order they are taken. While I've not seen a guarantee from the rxjs team that this will always be the case, I imagine changing this would break a lot of code (mine included).

Strictly speaking, no, no guarantee is made regarding subscription processing order. This goes back to Rx under .NET, when the team tried to align the subscription behavior with that of multicast delegates (you can find a good explanation from Bart De Smet at https://social.msdn.microsoft.com/Forums/en-US/ac721f91-4dbc-40b8-a2b2-19f00998239f/order-of-subscriptions-order-of-observations?forum=rx).

I have run across scenarios before where the "process in subscription order" hasn't suited me, and I've needed to take direct control. In this case, I've used a simple function to turn one observable into two, one of which is guaranteed to be notified before the other. You could use a similar method to avoid making the assumption that subscriptions will always be processed in order, though I personally do not think it's necessary. If interested, you can find details here: RxJs: Drag and Drop example : add mousedragstart

Upvotes: 2

Mike Tung
Mike Tung

Reputation: 4821

In terms of behaviorSubject, and subjects in general, they are "Hot" Observables that produce and consume values. You can assume that the next function will always trigger so long as nothing calls the observer.complete() method.

The first subscription you have will set and initialize the state (assumption here) and so every subsequent subscriber will be able to hook in to that subscription and ascertain the next(value) emissions.

Hope this helps.

Upvotes: -1

Related Questions