Last active
October 24, 2020 02:27
-
-
Save MelbourneDeveloper/265a8ddfc94394b528f415c4ab0a6a93 to your computer and use it in GitHub Desktop.
An example of simple messaging with observables
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
/* | |
One: Hi | |
Two: Hi | |
One: Hi | |
Two: Hi | |
One: Hi | |
Two: Hi | |
One: Hi | |
Two: Hi | |
One: Hi | |
Two: Hi | |
One: Hi | |
Two: 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 | |
{ | |
public class Subscriber : IObserver<string> | |
{ | |
Action<string> _action; | |
public Subscriber(Action<string> action) => _action = action; | |
public void OnCompleted() { } | |
public void OnError(Exception error) { } | |
public void OnNext(string value) => _action(value); | |
} | |
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 subscriber1 = new Subscriber((message) => Debug.WriteLine($"One: {message}")); | |
var subscriber2 = new Subscriber((message) => Debug.WriteLine($"Two: {message}")); | |
var publisher = new Publisher(); | |
publisher.Subscribe(subscriber1); | |
publisher.Subscribe(subscriber2); | |
await Task.Delay(3000); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment