Last active
September 10, 2015 20:06
-
-
Save georgebearden/8f9da296a16a53668222 to your computer and use it in GitHub Desktop.
How to create an IObservable that returns the same instance of the observable for each subscription
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
| public class SingletonObservable : IObservable<DateTime>, IDisposable | |
| { | |
| private readonly Subject<DateTime> _subject = new Subject<DateTime>(); | |
| private bool _isRunning = true; | |
| public SingletonObservable() | |
| { | |
| InstanceCount++; | |
| Task.Run( async () => | |
| { | |
| while ( _isRunning ) | |
| { | |
| _subject.OnNext( DateTime.Now ); | |
| await Task.Delay( 100 ); | |
| } | |
| } ); | |
| } | |
| public void Dispose() | |
| { | |
| _isRunning = false; | |
| } | |
| public IDisposable Subscribe( IObserver<DateTime> observer ) | |
| { | |
| return _subject.Subscribe( observer ); | |
| } | |
| public static int InstanceCount { get; private set; } | |
| } | |
| [Test] | |
| public void HowToReturnSameObservableImplOnSubscribe() | |
| { | |
| var singletonObservable = new SingletonObservable(); | |
| var subscription1 = singletonObservable.Subscribe( _ => { } ); | |
| Assert.AreEqual( 1, SingletonObservable.InstanceCount ); | |
| var subscription2 = singletonObservable.Subscribe( _ => { } ); | |
| Assert.AreEqual( 1, SingletonObservable.InstanceCount ); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment