Skip to content

Instantly share code, notes, and snippets.

@nantcom
Created April 25, 2021 12:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nantcom/28db47215ec3d6afcf84dfa550ac0b59 to your computer and use it in GitHub Desktop.
Save nantcom/28db47215ec3d6afcf84dfa550ac0b59 to your computer and use it in GitHub Desktop.
Sample for Rx Blog - Using Rx to Create more readable timer which stops when no one is listening
#r "nuget:System.Reactive/5.0.0"
using System.Reactive.Linq;
public class TimeStopWhenNoOneCares
{
private IObservable<long> _Interval;
private long _Time;
public IDisposable ObserveTime( Action<long> subscriber )
{
if (_Interval == null)
{
_Interval = Observable.Create<long>( observer => {
bool stop = false;
Task.Run( ()=>{
while (!stop)
{
observer.OnNext(_Time);
Task.Delay(1000).Wait();
_Time++;
}
});
// return function to call when observable was being destroyed
return ()=>
{
_Interval = null;
stop = true;
};
}).Replay(1).RefCount(1);
}
return _Interval.Subscribe( subscriber );
}
}
TimeStopWhenNoOneCares t = new();
var observer = t.ObserveTime( time =>{
Console.WriteLine( time);
});
Console.ReadLine();
observer.Dispose();
Console.WriteLine( "Time stop" );
Console.ReadLine();
Console.WriteLine( "Time continue from last value" );
t.ObserveTime( time =>{
Console.WriteLine( time);
});
Console.ReadLine();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment