I have a replay subject, and it is subscribed in multiple components. I just want to know in what order the subscription goes.
public getValue$ = new ReplaySubject<any>(1);
If I broadcast a value to getValue$ by
getValue$.next(5);
And, let’s say, getValue$ is subscribed in a, b, c and few other components. b is the child component of a and c is a sibling of a. How is the sequence decided?
I believe that they will be updated in the order that they subscribed, but I wouldn't trust that is always the case. I imagine that an observable stores its observers in a simple array and just pushes the next subscription to the array. I could be totally wrong about that though.
Writing code that depends on the order of subscriptions though is dangerous and likely to lead to problems. An observable is intended to be asynchronous, so it could be that the order subscriptions are triggered isn't consistent. I would not write code in a way that it assumes or requires that subscriptions would be triggered in any particular order.
If you need to react to new data from multiple observables, consider using RXJS operators built for this purpose, like
combineLatest
,merge
, andforkJoin
, to avoid race conditions.