In .NET I've been essentially raised to never ever forget to unsubscribe to events. In MVVM apps what I often end up with is this construct.
public class WindowVm
{
public EntityModel MyModel { get; set; }
void Subscribe()
{
MyModel.PropertyChanged += DoSomething;
}
void Unsubscribe()
{
MyModel.PropertyChanged -= DoSomething;
}
}
I need to unsubscribe, because if I don't MyModel would keep a reference to the WindowVm and keep it alive for as long as MyModel lives.
I just found out about reactive extensions, but I can't find out whether I need to still think about this. I cant find anywhere that says so, but I also don't hear "oh and btw it solves that annoying event unsubscribe problem" which would be a killer argument.
public class WindowVm
{
public EntityModel MyModel { get; set; }
void Subscribe()
{
MyModel.PropChangedObservable.Subscribe(e => DoSomething(e.Sender, e.EventArgs));
}
}
public class EntityModel : ObservableBase
{
public IObservable<EventPattern<PropertyChangedEventArgs>> PropChangedObservable { get; private set; }
public EntityModel()
{
PropChangedObservable = Observable
.FromEventPattern<PropertyChangedEventHandler, PropertyChangedEventArgs>(
x => this.PropertyChanged += x,
x => this.PropertyChanged -= x);
}
}
I can't tell whether this would create an extra reference. And what about this way?
public class WindowVm
{
public EntityModel MyModel { get; set; }
void Subscribe()
{
Observable
.FromEventPattern<PropertyChangedEventHandler, PropertyChangedEventArgs>(
x => MyModel.PropertyChanged += x,
x => MyModel.PropertyChanged -= x)
.Subscribe(e => DoSomething(e.Sender, e.EventArgs));
}
}
question from:
https://stackoverflow.com/questions/65863688/do-i-have-to-worry-about-memory-leaks-with-rx-net-fromeventpattern 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…