What I would like to do is:
- Call a function (
DoWork
) which as part of it's work will subscribe to multiple hot inputs through multipleWorker
classes - Before calling the function subscribe to all the updates that
DoWork
subscribes to - Once finished, dispose of all the subscriptions
- It is probable that at least one incoming event will fire before
DoWork
has completed.
Questions:
- Are
Subject
s the correct way to do this? It feels like there should be a better way? How to ensure that once the subscription in
Main
is disposed, all of theincomingX
subscriptions are also disposed - i.e.Main
should control the lifecycle of all the subscriptions.void Main() { var worker = new Worker(); using (worker.UpdateEvents.Subscribe(x => Console.WriteLine())) { worker.DoWork(); } } public class Worker1 { private readonly Subject<string> updateEvents = new Subject<string>(); public IObservable<string> UpdateEvents { get { return updateEvents; } } public void DoWork() { // Do some work // subscribe to a hot observable (events coming in over the network) incoming1.Subscribe(updateEvents); var worker2 = new Worker2(); worker2.UpdateEvents.Subscribe(updateEvents); worker2.DoWork(); } } public class Worker2 { private readonly Subject<string> updateEvents = new Subject<string>(); public IObservable<string> UpdateEvents { get { return updateEvents; } } public void DoWork() { // Do some work // subscribe to some more events incoming2.Subscribe(updateEvents); var workerN = new WorkerN(); workerN.UpdateEvents.Subscribe(updateEvents); workerN.DoWork(); } }