how to convert IEnumerable to IObservable?

后端 未结 2 1680
深忆病人
深忆病人 2021-02-06 04:41

I\'m looking to convert an IEnumerable collection to an IObservable one without using Rx ToObservable() and ToEnumerable() methods.

2条回答
  •  温柔的废话
    2021-02-06 05:27

    Simple answer - use ToObservable. That's what it's for.

    "Answering the actual question" answer - you can avoid using Subjects via Observable.Create:

    void Main()
    {
        var src = Enumerable.Range(0, 10);
        var observable = Observable.Create(obs =>
        {
            foreach(var item in src)
            {
                obs.OnNext(item);
            }
            return Disposable.Create(()=>{});
        });
    
        using(observable.Subscribe(Console.WriteLine))
        {
            Console.ReadLine();
        }
    }
    

    Output:

    0
    1
    2
    3
    4
    5
    6
    7
    8
    9
    

提交回复
热议问题