Last active
October 24, 2020 02:35
-
-
Save MelbourneDeveloper/0bf4eaf9078e4a1395109f4a6b84e38f to your computer and use it in GitHub Desktop.
An example of simple messaging with observable
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 | |
*/ | |
using Microsoft.VisualStudio.TestTools.UnitTesting; | |
using System; | |
using System.Collections.Generic; | |
using System.Diagnostics; | |
using System.Reactive.Disposables; | |
using System.Threading.Tasks; | |
namespace UnitTestProject1 | |
{ | |
class Subscriber | |
{ | |
public string Name; | |
//Listen for OnNext and write to the debug window when it happens | |
public Subscriber(IObservable<string> observable, string name) | |
{ | |
Name = name; | |
var disposable = observable.Subscribe((s) => Debug.WriteLine($"Name: {Name} Message: {s}")); | |
} | |
} | |
public class Publisher : IObservable<string> | |
{ | |
List<IObserver<string>> _observers = new List<IObserver<string>>(); | |
public Publisher() | |
{ | |
Task.Run(async () => | |
{ | |
//Loop forever | |
while (true) | |
{ | |
//Get some data, publish it with OnNext and wait 500 milliseconds | |
_observers.ForEach(o => o.OnNext(GetSomeData())); | |
await Task.Delay(500); | |
} | |
}); | |
} | |
private string GetSomeData() => "Hi"; | |
public IDisposable Subscribe(IObserver<string> observer) | |
{ | |
_observers.Add(observer); | |
return Disposable.Create(() => { }); | |
} | |
} | |
[TestClass] | |
public class UnitTest1 | |
{ | |
[TestMethod] | |
public async Task Messaging() | |
{ | |
var publisher = new Publisher(); | |
new Subscriber(publisher, "One"); | |
new Subscriber(publisher, "Two"); | |
await Task.Delay(3000); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment