c# - Is ordering guaranteed by call-order cross multiple Rx Subjects? -
in example below have 2 subjects , _primarysubject called before _secondarysubject subscriber guaranteed receive primary callback before secondary callback? test simple test seems yes or fluke?
and if fluke how can change code guarantee order describe here.
thanks lot.
public class eventgenerator { isubject<string> _primarysubject = new subject<string>(); isubject<int> _secondarysubject = new subject<int>(); private int i; public void sendevent(string message) { _primarysubject.onnext(message); _secondarysubject.onnext(i++); } public iobservable<string> getprimarystream() { return _primarysubject; } public iobservable<int> getsecondarystream() { return _secondarysubject; } } public class eventsubscriber { private static ischeduler staticfakeguithread = new eventloopscheduler(x => new thread(x) { name = "guithread" }); private readonly int _id; public eventsubscriber(int id, eventgenerator eventgenerator) { _id = id; eventgenerator.getprimarystream().observeon(staticfakeguithread).subscribe(onprimaryevent); eventgenerator.getsecondarystream().observeon(staticfakeguithread).subscribe(onsecondaryevent); } private void onprimaryevent(string eventmsg) { string msg = eventmsg; } private void onsecondaryevent(int i) { int msg = i; } } [testfixture] public class eventgeneratortest { [test] public void test() { eventgenerator eg = new eventgenerator(); eventsubscriber s1 = new eventsubscriber(1,eg); eventsubscriber s2 = new eventsubscriber(2, eg); eg.sendevent("a"); eg.sendevent("b"); } }
in general, rx not make many guarantees relative ordering of different observable streams. ordering dependent upon many factors beyond control of rx.
in specific case, ordering guaranteed:
- since trigger subjects synchronously in order, guaranteed immediate subscriptions (
.observeon(staticfakeuithread)
) triggered in order. - since use same scheduler instance both calls
observeon
, guaranteed observation of primary stream event scheduled before observation of secondary stream event , both observations scheduled same scheduler - since scheduler
eventloopscheduler
, guaranteed not run scheduled tasks concurrently, instead run them in order in scheduled.
thus observations indeed run in order.
replace eventloopscheduler
taskpoolscheduler
, threadpoolscheduler
, or scheduler.default
, there no longer guarantees on relative ordering of 2 streams because schedulers allowed run 2 scheduled tasks concurrenly.
Comments
Post a Comment