0

I wonder what is the best way to get the latest element in a sequence before the Timeout fires?

I have a code that ping the remote services from time to time and I want to be able to identify one that has gone offline.

Using the Timeout extension I came up to this:

heartbeatResponseObservable.Timeout(Timeout, Observable.Return(new HeartbeatBusMessage.Timeout()))

This kinda work but it doesn't allow me to find which service has gone. What I'd like to have is the Timeout extension with the latest message in the stream as an argument to provide some information in the error message it produce.

How do I get the latest sequence element inside the Timeout extension?

Dmitrii
  • 321
  • 6
  • 17
  • Do they all need to funnel through the same Observable? – paulpdaniels Sep 26 '15 at 07:44
  • @paulpdaniels not really. I have separate streams for 'send' messages and for 'recieved' messages. what I need to catch - is a situation when there is no pair for 'send' message in the 'recieved' stream for X time interval. – Dmitrii Sep 26 '15 at 10:47

1 Answers1

1
public static IObservable<T> TimeOutExtension<T>(
    this IObservable<T> source, 
    TimeSpan timeSpan)
{
    // On Timeout complete with an empty Observable.
    var completeOnTimeout = source
                                .Timeout(timeSpan)
                                .Catch<T, TimeoutException>(ex => Observable.Empty<T>());

    // Join the source w/ the empty Observable created on timeout.
    var beforeTimeout =
        source.Join(completeOnTimeout, 
        _ => source, 
        _ => completeOnTimeout, 
        (s, c) => s);

    // Return last
    return beforeTimeout.LastAsync();
}

Could be used like this:

// Create 10 events quickly, then once every two seconds.
var source =
    Observable.Interval(TimeSpan.FromMilliseconds(100))
        .Take(10)
        .Concat(Observable.Interval(TimeSpan.FromSeconds(2)));

// Set a timeout of 1 second.
var last = source.TimeOutExtension(TimeSpan.FromSeconds(1));

last.Subscribe(Console.WriteLine); // outputs 9
voqk
  • 178
  • 9