创建IObservables 的方法

一些原始方法

IObservable obs = Observable.Empty();
IObservable obs = Observable.Return(0);
IObservable obs = Observable.Throw(new Exception());
IObservable obs = Observable.Never();

简单的流

IObservable obs = Observable.Interval(new TimeSpan(0, 0, 1));
IObservable obs = Observable.Timer(DateTimeOffset.Now.AddHours(1)); 
IObservable obs = Observable.Repeat(1); 
IObservable obs = Observable.Range(0, 1);

从异步数据

//从Action或者Func
Observable.Start(() => 1);
//从Task
Task.Factory.StartNew(...).ToObservable();
//从AsyncPattern
Func sampleFunc = (a,b) => 1d;
Func> funcObs = 
                  Observable.FromAsyncPattern(sampleFunc.BeginInvoke, 
                                                                      sampleFunc.EndInvoke);
IObservable obs = funcObs(1, 0);

从事件

public event EventHandler AnEvent;
IObservable> fromEventObs = 
Observable.FromEvent(h => this.AnEvent += h, h=>this.AnEvent -= h);

从已有的集合

IEnumerable ie = new int[] {};
observable = ie.ToObservable();

通过Generate()
通过Create()
-->冷流

IObservable observable = Observable.Create(o =>
                                {
                                    o.OnNext(1);
                                    o.OnNext(2);
                                    o.OnCompleted();
                                    return () => { };
                                });

-->热流

List> _subscribed = new List>();
private CreateHot()
{
    observable = Observable.Create(o =>
    {
        _subscribed.Add(o);
        return () => _subscribed.Remove(o);
    });

}
private void onNext(int val)
{
    foreach (var o in _subscribed)
    {
        o.OnNext(val);
    }
}

你可能感兴趣的:(创建IObservables 的方法)