Last active
October 25, 2020 06:03
-
-
Save MelbourneDeveloper/0e967865f95b249c30b0f47d9da6cb87 to your computer and use it in GitHub Desktop.
Hot observable implementation which is modification of Enigmativity's sample
This file contains 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
/* | |
Name: One Message: Hi | |
Name: Two Message: Hi | |
Name: One Message: Hi | |
Name: Two Message: Hi | |
Name: One Message: Hi | |
Name: Two Message: Hi | |
Name: One Message: Hi | |
Name: Two Message: Hi | |
Name: One Message: Hi | |
Name: Two Message: Hi | |
Name: One Message: Hi | |
Name: Two Message: Hi | |
This sample is a modification of Enigmativity's code | |
Stack Overflow: https://stackoverflow.com/a/64520014/1878141 | |
*/ | |
using Microsoft.VisualStudio.TestTools.UnitTesting; | |
using System; | |
using System.Diagnostics; | |
using System.Reactive.Disposables; | |
using System.Reactive.Linq; | |
using System.Threading.Tasks; | |
namespace Observables | |
{ | |
class Subscriber : IDisposable | |
{ | |
public string Name; | |
private IDisposable _disposable; | |
//Listen for OnNext and write to the debug window when it happens | |
public Subscriber(IObservable<string> observable, string name) | |
{ | |
Name = name; | |
_disposable = observable.Subscribe((s) => Debug.WriteLine($"Name: {Name} Message: {s}")); | |
} | |
public void Dispose() => _disposable.Dispose(); | |
} | |
[TestClass] | |
public class UnitTest1 | |
{ | |
private static string GetData() => "Hi"; | |
[TestMethod] | |
public async Task Messaging() | |
{ | |
var coldObservable = | |
Observable | |
.Timer(TimeSpan.Zero, TimeSpan.FromSeconds(1.0)) | |
.Select(_ => GetData()); | |
var publisher = coldObservable.Publish(); | |
//Note that we might miss some notifications here. This is because we subscribe after calling the publish method. | |
//If want to avoid this we would have to rewrite the code in a similar way to Enigmativity's code. | |
var subscriptions = | |
new CompositeDisposable( | |
new Subscriber(publisher, "One"), | |
new Subscriber(publisher, "Two")); | |
var connection = publisher.Connect(); | |
await Task.Delay(TimeSpan.FromSeconds(5.0)); | |
//Disconnect the subscriptions | |
subscriptions.Dispose(); | |
//Stop the observable | |
connection.Dispose(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment