Skip to content

Instantly share code, notes, and snippets.

@MelbourneDeveloper
Last active October 24, 2020 02:35
Show Gist options
  • Save MelbourneDeveloper/0bf4eaf9078e4a1395109f4a6b84e38f to your computer and use it in GitHub Desktop.
Save MelbourneDeveloper/0bf4eaf9078e4a1395109f4a6b84e38f to your computer and use it in GitHub Desktop.
An example of simple messaging with observable
/*
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