Created
October 24, 2020 05:19
-
-
Save MelbourneDeveloper/c0f08800e3f7aaed63929b299d54b228 to your computer and use it in GitHub Desktop.
This version creates two threads and loops. It's no good.
This file contains hidden or 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: Two Message: Hi | |
Name: One Message: Hi | |
Name: Two Message: Hi | |
Name: One Message: Hi | |
*/ | |
using Microsoft.VisualStudio.TestTools.UnitTesting; | |
using System; | |
using System.Diagnostics; | |
using System.Reactive.Concurrency; | |
using System.Reactive.Disposables; | |
using System.Reactive.Linq; | |
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}")); | |
} | |
} | |
[TestClass] | |
public class UnitTest1 | |
{ | |
[TestMethod] | |
public async Task Messaging() | |
{ | |
var publisher = | |
Observable.Create<string>(observer => | |
{ | |
var cancel = new CancellationDisposable(); | |
NewThreadScheduler.Default.Schedule(async () => | |
{ | |
while (true) | |
{ | |
await Task.Delay(500); | |
if (cancel.Token.IsCancellationRequested) | |
{ | |
observer.OnCompleted(); | |
return; | |
} | |
observer.OnNext(GetData()); | |
} | |
}); | |
return cancel; | |
}); | |
new Subscriber(publisher, "One"); | |
new Subscriber(publisher, "Two"); | |
await Task.Delay(3000); | |
} | |
private string GetData() => "Hi"; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment