I have the following code
static void Main(string[] args)
{
//var source = BlockingMethod();
var source2 = NonBlocking();
source2.Subscribe(Console.WriteLine);
//source.Subscribe(Console.WriteLine);
Console.ReadLine();
}
private static IObservable<string> BlockingMethod()
{
var subject = new ReplaySubject<string>();
subject.OnNext("a");
subject.OnNext("b");
subject.OnCompleted();
Thread.Sleep(1000);
return subject;
}
private static IObservable<string> NonBlocking()
{
return Observable.Create<string>(
observable =>
{
observable.OnNext("c");
observable.OnNext("d");
observable.OnCompleted();
//Thread.Sleep(1000);
var source = BlockingMethod();
source.Subscribe(Console.WriteLine);
return Disposable.Create(() => Console.WriteLine("Observer has unsubscribed"));
//or can return an Action like
//return () => Console.WriteLine("Observer has unsubscribed");
});
}
}
which prints
c
d
Observer has unsubscribed
a
b
Can anyone help me get the flow of the control in the program. I did try reading the Call Stack etc..but could not understand everything.
EDIT
Why do i get the above output(which i assume is right) instead of
c
d
a
b
Observer has unsubscribed
The difference in your expected behaviour and the actual behaviour comes from the following line:
By default a
ReplaySubjectuses theScheduler.CurrentThread. It’s as if you declared it like so:When scheduling using the current thread you get your actions queued up – waiting for the currently executing code to complete before it starts. If you want the code to run immediately you need to use
Scheduler.Immediatelike so:Does this explain it sufficiently?