2

Let's assume we had this observable sequence (RX) and matching subscription:

var behaviorSubject = new BehaviorSubject<int>(3);
var sequence = behaviorSubject.Select(x => this.webservice.Call(x)).Switch();
var subscription = this.sequence.Subscribe(this.Subject.OnNext, this.OnSequenceFaulted);

The sequence is meant to do a webservice call each time the behaviorSubject emits a new value, while cancelling previous requests. If an exception occurs during the webservice call, the subscription will be terminated (after calling the OnSequenceFaulted method).

Is it a good practice to implement the OnSequenceFaulted method like this? Do we need to restart (reassign) the sequence as well as the subscription, given that the exception originated from the observable within the sequence? And does a faulted subscription need to be explicitly disposed?

public void OnSequenceFaulted(Exception e)
{
    subscription?.Dispose();
    subscription = sequence.Subscribe(this.Subject.OnNext, this.OnSequenceFaulted);
}
Ehssan
  • 739
  • 6
  • 15

1 Answers1

1

As far as good practice goes that really depends on your use case and what you want to happen if the webservice.Call throws an exception.

To address specific parts of your question though around rx here are some good references Reactive Observable Subscription Disposal

If the observable completes - with either OnCompleted or OnError - then the subscription is already disposed for you.

introtorx here has a great description of various error handling techniques and what might apply in your scenario

http://www.introtorx.com/content/v1.0.10621.0/11_AdvancedErrorHandling.html

As far as how to handle your specific scenario there are a few options and here are just a couple thoughts

  1. you could just handle the exception on webcall itself so that it doesn't transition the stream to OnError http://www.introtorx.com/content/v1.0.10621.0/11_AdvancedErrorHandling.html#CatchSwallowingException

    var sequence = behaviorSubject.Select(x => this.webservice.Call(x)
              .Catch((Exception exc) => 
                   //do something with exception, 
                   //maybe just return an empty observable and log the exception
              ).Switch();
    
  2. You could also just tell it to retry http://www.introtorx.com/content/v1.0.10621.0/11_AdvancedErrorHandling.html#Retry

    var subscription = this.sequence.Retry().Subscribe(this.Subject.OnNext, this.OnSequenceFaulted);
    

There's not really a specific Rx best practice AFAIK. It's really just about what you want to happen if an exception happens. If you don't care at all and just want it to live on then a Retry is fine. If you want to catch and log then you can put the catch on the webservice call. If you want to inspect the exception and then have different exceptions cause different out comes you can put different catch's on the webservice call.

Community
  • 1
  • 1
Shane Neuville
  • 2,127
  • 14
  • 19