I'm learning Rx-stuff and I've made a test app, which has a shared counter state and dynamically created counter widgets. Such as you can press add/remove buttons to spawn/destroy a new counter. It works fine, but I don't know how to correctly dispose removed counter widgets.
Here is my source code.
One part of a problem is at line 77:
// update each counter's label
addCounterStream.Subscribe(x => {
counterState.Subscribe(q => x.Counter = q.ToString()); // How can I unsubscribe later?
});
And the possible solution, I can think of, is to create a Subject<IDisposable>
which will collect these subscriptions and then combine this stream with removeCounterStream
and do unsibscribe.
But another part of a problem is at lines 40, 41:
var incFromWidget = addCounterStream.SelectMany(x => Observable.FromEventPattern(x, "Increment").Select(_ => 1));
var decFromWidget = addCounterStream.SelectMany(x => Observable.FromEventPattern(x, "Decrement").Select(_ => -1));
It merges click events from all dynamically created widgets. What will happen if I want to remove some widget? It will disappear from the form and so won't be able to produce new click events, but it can not be GC
'ed, because it still hold references to click events (because of FromEventPattern
).
That is a memory leak, am I right?
So, the question is how to correctly deal with Observables of objects that can be added/removed dynamically?