Reactive Framework Hello World

This is a simple program for implementing the Reactive Framework . But I want to try the error handler by changing the program as follows:

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();

This example uses reloading overload.

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

I was hoping to see an exception message, but the console application crashed. What is the reason?

+3
source share
3 answers

An exception handler is used for exceptions thrown by the observer himself, and not by the observer.

An easy way to trigger an 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");
    }
}

Conclusion:

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
+5
source

Rx- , , IObservable (Select, Where, GroupBy ..), OnError , . , .

, Observer, . , , .

+3

Is it really a failure or is Visual Studio jumping and showing that an exception has occurred? If the second is true, you should take a look at Debug - Exception in the menu bar and deselect everything on the right.

0
source

Source: https://habr.com/ru/post/1754378/


All Articles