Skip to content

Instantly share code, notes, and snippets.

@georgebearden
Last active September 10, 2015 20:06
Show Gist options
  • Select an option

  • Save georgebearden/8f9da296a16a53668222 to your computer and use it in GitHub Desktop.

Select an option

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
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