Skip to content

Instantly share code, notes, and snippets.

@rogeralsing
Last active August 29, 2015 14:01
Show Gist options
  • Save rogeralsing/fe5a57ad7308332a4334 to your computer and use it in GitHub Desktop.
Save rogeralsing/fe5a57ad7308332a4334 to your computer and use it in GitHub Desktop.
var chatMessages = GetObservableOfChatMessages();
var chatIsIdle = chatMessages. _dontknow_ (TimeSpan.FromSeconds(5));
chatMessages.Subscribe (msg => Console.WriteLine("{0} says: {1}",msg.User,msg.Text));
//I want this to occur every time the chatmessages observable have been silent for 5 sec
//not just once
chatIsIdle.Subscribe ( ... => Console.WriteLine("Chat is idle...");
@mattpodwysocki
Copy link

Easiest way would be to create a timer for this, run it until a chat message fires, and then rinse and repeat, eg:

var chatMessages = GetObservableOfChatMessages();
var chatIsIdle = Observable.Timer(TimeSpan.FromSeconds(5))
    .TakeUntil(chatMessages)
    .Repeat();

chatMessages.Subscribe (msg => Console.WriteLine("{0} says: {1}",msg.User,msg.Text));

//I want this to occur every time the chatmessages observable have been silent for 5 sec
//not just once
chatIsIdle.Subscribe ( ... => Console.WriteLine("Chat is idle...");

@headinthebox
Copy link

Nice @mattpodwysocki. Could also use timeout.

@rogeralsing
Copy link
Author

This almost does what I want, however, this will repeat the "Chat is idle..." every 5 sec.
I only want one such notification 5 sec after the chat message, and if the chat is again active and then idles again, I want a new idle message..

e.g.

x: hello
y: hi
-5 sec passes..
chat is idle...
-100 sec passes.. the idle message should not repeat here

x: Im back
y: nice
-5 sec passes
chat is idle...

@richkeenan
Copy link

You could make an extension method, BufferUntilInactive

public static IObservable<IList<T>> BufferUntilInactive<T>(this IObservable<T> stream, TimeSpan delay)
{
    var closes = stream.Throttle(delay);
    return stream.Window(() => closes).SelectMany(window => window.ToList());
}

And just ignore the return values, so your above code looks like

var chatIsIdle = chatMessages.BufferUntilInactive(TimeSpan.FromSeconds(5));
chatIsIdle.Subscribe ( _ => Console.WriteLine("Chat is idle...");

I got this from a similar question I asked on SO a while back, so credit to Colonel Panic for his answer, http://stackoverflow.com/q/8849810/255231

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment