Observable.Min/Max throw Exception on Empty Stream?


  • Is the expected behavior to throw an exception if the stream is empty when running min/max?

    Other than using minBy/maxBy how can I test to ensure values exists and run min/max on a hot stream if there is potential for the sequence to be empty?

    Tuesday, August 06, 2013 3:19 PM

All replies

  • What are you hoping to see when you get an empty sequence. IMO you are taking a set of many and reducing it to a set of 1. If the set is empty, what would the single value be?

    If you have an answer for that then sweet!

    2 options I can think of are:

    1) If the source sequence is empty, then the output sequence should be empty

    var source = Observable.Empty<int>();
    //source.Min() causes OnError(InvalidOperationEx)
    //Empty sequence with MinBy
    //Empty sequence with Catch/Swallow
          .Catch((InvalidOperationException ex)=>Observable.Empty<int>())

    2) Return a default min value if empty (0, null, etc...)

    var defaultValue = 0;
    var source = Observable.Empty<int>();
    //Catch error and continue with default value.
    	  .Catch((InvalidOperationException ex)=>Observable.Return<int>(defaultValue))

    So yeah, it is a bit weird that MinBy does something different to Min. But here are some options for you.


    Lee Campbell

    • Proposed as answer by Dave Sexton Tuesday, August 06, 2013 5:19 PM
    • Marked as answer by Davewolfs Tuesday, August 06, 2013 9:15 PM
    • Unmarked as answer by Davewolfs Tuesday, August 06, 2013 9:54 PM
    Tuesday, August 06, 2013 3:45 PM
  • Your suggestions of swallowing the exception seems like exactly what I want.  In fact since MinBy just returns a list I am checking to see if the list is at least a length > 0 (Where(fun x -> x.Count > 0)) and if so than I am returning the first value in my list.

    New to RX so did not even consider swallowing the exception.


    • Edited by Davewolfs Tuesday, August 06, 2013 9:15 PM
    Tuesday, August 06, 2013 9:14 PM