Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reactive Framework Hello World

This is an easy program to introduce the Reactive Framework. But I want to try the error handler, by modifying the program to be:

var cookiePieces = Observable.Range(1, 10);
cookiePieces.Subscribe(x =>
   {
      Console.WriteLine("{0}! {0} pieces of cookie!", x);
      throw new Exception();  // newly added by myself
   },
      ex => Console.WriteLine("the exception message..."),
      () => Console.WriteLine("Ah! Ah! Ah! Ah!"));
Console.ReadLine();

In this sample the follwing overload is used.

public static IDisposable Subscribe<TSource>(
     this IObservable<TSource> source, 
     Action<TSource> onNext, 
     Action<Exception> onError, 
     Action onCompleted);

I hoped I would see the exception message printed, but the console application crashed. What is the reason?

like image 845
Cheng Chen Avatar asked Feb 12 '26 19:02

Cheng Chen


2 Answers

The exception handler is used for exceptions created in the observable itself, not by the observer.

An easy way to provoke the exception handler is something like this:

using System;
using System.Linq;

class Test
{
    static void Main(string[] args)
    {
        var xs = Observable.Range(1, 10)
                           .Select(x => 10 / (5 - x));

        xs.Subscribe(x => Console.WriteLine("Received {0}", x),
                     ex => Console.WriteLine("Bang! {0}", ex),
                     () => Console.WriteLine("Done"));

        Console.WriteLine("App ending normally");
    }
}

Output:

Received 2
Received 3
Received 5
Received 10
Bang! System.DivideByZeroException: Attempted to divide by zero.
   at Test.<Main>b__0(Int32 x)
   at System.Linq.Observable.<>c__DisplayClass35a`2.<>c__DisplayClass35c.<Select
>b__359(TSource x)
App ending normally
like image 171
Jon Skeet Avatar answered Feb 15 '26 09:02

Jon Skeet


In the Rx library, any user code passed into an operator that works on IObservable (Select, Where, GroupBy etc...) will be caught and send to the OnError handler of observers subscribed to the observable. The reason these are handled is that they are part of the computation.

Exceptions occurring in Observer code will have to be handled by the user. As they're at the end of the computation, it is unclear to Rx how to handle these.

like image 38
Jeffrey van Gogh Avatar answered Feb 15 '26 07:02

Jeffrey van Gogh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!