Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

For Observable, is the subscribe order guaranteed to be the same as the order of notification?

I wonder if, given the following RX code:

myObservable.subscribe(obs1)
myObservable.subscribe(obs2)

... it is guaranteed that obs1.onNext is called before obs2.onNext

PS: From my perspective it's bad practice to write code that relies on the subscribe order but I'm curious if there is any such guarantee somewhere in the RX documentation.

Thanks

like image 748
vidi Avatar asked Jun 14 '17 13:06

vidi


1 Answers

Why don't you read the documentation?

The answer is though, that it depends.

If myObservable is an observable that creates a brand new pipeline when a subscriber comes along then there is no guarantee that they will called in any order.

For example, Observable.Interval(TimeSpan.FromSeconds(1.0)) will create a brand new pipeline when a subscriber comes along. Two subscribers then two pipelines.

However, if myObservable is a Subject<int> then the order in which the observers attach is the key. Only one observer will receive values at a time and it will be done in sequence. This is a shared pipeline for all subscribers.

You can always take Observable.Interval(TimeSpan.FromSeconds(1.0)) and add .Publish() to the end. Then you get an observable that acts like a Subject<int> and can have multiple observers for the one source.

like image 53
Enigmativity Avatar answered Oct 03 '22 23:10

Enigmativity