This is part I of the Rx sequence generation, where in this topic we will discuss the topic of how to generating sequence.
Typically there are Range method, there is Create method which takes Action<T>, and there are many others, an example is a extension method that used to generate infinite sequence of Items.
Observable.Create method.
In Sequence Basic , There are overloaded method that can help you to generate a sequence out of the Create method of Observable.
/Creates an observable sequence from a specified Subscribe method implementation.
public static IObservable<TSource> Create<TSource>(
Func<IObserver<TSource>, IDisposable> subscribe)
{...}
public static IObservable<TSource> Create<TSource>(
Func<IObserver<TSource>, Action> subscribe)
{...}
public static IObservable<TSource> Create<TSource>(
Func<IObserver<TSource>, IDisposable> subscribe)
{...}
Method, but according to the "
Why is the argument to Observable.Create a Func<IObserver<T>, Action>)"
Create is nearly identical, only it executes the Action when the subscription is disposed.Here is a example code that I used based on response.
class Program {
public static void Main(string[] args)
{
Program program = new Program();
//program.BlockingMethod();
var nonBlockiongObservable= program.NonBlocking();
nonBlockiongObservable.Subscribe(
onNext: x => { Console.WriteLine("Coming {0}", x); },
onCompleted: () => { Console.WriteLine("Done.. "); },
onError: x => { Console.WriteLine("Errors: " + x); }
);
Console.WriteLine("...");
Console.ReadLine();
}
private IObservable<string> NonBlocking()
{
return Observable.Create<string>(
(IObserver<string> observer) =>
{
observer.OnNext("a");
observer.OnNext("b");
observer.OnCompleted();
Thread.Sleep(1000);
//return Disposable.Create(() => Console.WriteLine("Observer has unsubscribed"));
// will this be used by IDisposable as the action to invoke ??
return () => Console.WriteLine("Observer has unsubscribed");
//or can return an Action like
//return () => Console.WriteLine("Observer has unsubscribed");
});
}
}
As you can see that "Observer has unsbuscribed" is called at the end of the run.
Implementing Observers and Subjects using IObserver/IObservable,
The static method Observable.Create<T>() is essentially a wrapper to AnonymousObservable<T>.
this helps explaining the difference.