开发者

handle OnCompleted with cold observables

in Rx, the following code does not seem to call my OnCompleted action?

No "Sequence Completed"

    static void Main(string[] args)
    {
        var list = new List<int> { 1, 2, 3 };
        var obs = list.ToObservable();
        IDisposable subscription = obs.SubscribeOn(Scheduler.NewThread).Subscribe(p =>
        {
            Console.WriteLine(p.ToString());
            Thread.Sleep(200);
        },
        p => Console.WriteLine("Sequence completed"));
        Console.ReadLine();
        subscription.Dispose();
    }

Am i doing something silly, as there is no "Sequence Completed" printed after 3 in the Console window?

Console Output

1
2
3
_

So, the prime focus of my question is how to run some code after this type of sequence has been iterated?

  • E.g. how to execute Console.WriteLine("Sequence completed")) after all elemen开发者_开发百科ts in the original list have been observed?
  • Please note that the .ToObservable originated from an IEnumerable (a List<> in this case)
  • And the subscription is run on a NewThread


The problem is that the 2nd parameter to .Subscribe is the error callback. Your "sequence completed" string would be printed only if there was an error observing the elements.

Here's the corrected code:

var list = new List<int> { 1, 2, 3 };
var obs = list.ToObservable();
var subscription = obs.SubscribeOn(Scheduler.NewThread).Subscribe(p =>
    {
        Console.WriteLine(p.ToString());
        Thread.Sleep(200);
    },
    error => Console.WriteLine("Error!"),
    () => Console.WriteLine("sequence completed"));
Console.ReadLine();
subscription.Dispose();
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜