testing the cancellation of a simple observable doesn't call onError

Viewed 142

Given the following:

Why is the OnError handler in Subscribe never called?

var observable = Observable.Create<string>(
    async (o, c) =>
    {
        try
        {
            var strings = new[] { "A", "B", "C" };

            foreach (var s in strings)
            {
                await Task.Delay(100);
                if (c.IsCancellationRequested)
                {
                    // exception thrown here.
                    Console.WriteLine("cancelled");
                    throw new OperationCancelledException();
                }
                o.OnNext(s);
            }
            o.OnCompleted();
        }
        catch (Exception ex)
        {
            // caught here...
            o.OnError(ex);
        }
    });

var tcs = new TaskCompletionSource<bool>();
var token = new CancellationTokenSource();
observable.Subscribe(
    str =>
    {
        Console.WriteLine(str);
        token.Cancel(); // cancel after the first iteration.
    },
    (e) =>
    {
        // why is this never called.
        Console.WriteLine($"on error :: {e.Message}");
        tcs.SetResult(true);
    },
    () =>
    {
        Console.WriteLine("on complete");
        tcs.SetResult(true);
    },
    token.Token);

// code hangs here because the subscription never completes?
await tcs.Task;
Console.WriteLine("done");
3 Answers
Related