Created
April 25, 2021 12:02
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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