Skip to content

Instantly share code, notes, and snippets.

@MelbourneDeveloper
Last active October 24, 2020 02:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save MelbourneDeveloper/265a8ddfc94394b528f415c4ab0a6a93 to your computer and use it in GitHub Desktop.
Save MelbourneDeveloper/265a8ddfc94394b528f415c4ab0a6a93 to your computer and use it in GitHub Desktop.
An example of simple messaging with observables
/*
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