C# Rx - Create a sequence - Series I

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)
{...}

In .NET 4. 0, I did not find the 

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.



转载于:https://my.oschina.net/u/854138/blog/110796

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值