How to handle exceptions in OnNext when using ObserveOn?

后端 未结 5 1242
自闭症患者
自闭症患者 2020-12-10 04:46

My application terminates when an error is thrown in OnNext by an observer when I use ObserveOn(Scheduler.ThreadPool). The only way I have found to

5条回答
  •  被撕碎了的回忆
    2020-12-10 05:22

    You're right - it should feel bad. Using and returning subjects like this is not a good way to go.

    At the very least you should implement this method like so:

    public static IObservable ExceptionToError(this IObservable source)
    {
        return Observable.Create(o =>
        {
            var subscription = (IDisposable)null;
            subscription = source.Subscribe(x =>
            {
                try
                {
                    o.OnNext(x);
                }
                catch (Exception ex)
                {
                    o.OnError(ex);
                    subscription.Dispose();
                }
            }, e => o.OnError(e), () => o.OnCompleted());
            return subscription;
        });
    }
    

    Notice there are no subjects used and that if I catch an error that I then dispose of the subscription to prevent the sequence continuing past an error.

    However, why not just add an OnError handler in your subscription. A bit like this:

    var xs = new Subject();
    
    xs.ObserveOn(Scheduler.ThreadPool).Subscribe(x =>
    {
        Console.WriteLine(x);
        if (x % 5 == 0)
        {
            throw new System.Exception("Bang!");
        }
    }, ex => Console.WriteLine(ex.Message));
    
    xs.OnNext(1);
    xs.OnNext(2);
    xs.OnNext(3);
    xs.OnNext(4);
    xs.OnNext(5);
    

    This code catches the error properly in the subscription.

    The other method is to use the Materialize extension method, but that may be a little overkill unless the above solutions don't work.

提交回复
热议问题