I have a view model which retrieves an object from some service, and makes it available for data binding. The object is implementing INotifyPropertyChanged
. In the view model, I am listening to the PropertyChanged
event to perform some internal actions when certain properties in the object are modified.
Now it is possible that a new object is requested from the service, completely replacing the old object. Given that the lifetime is essentially limited by the view model itself, and nobody else holds a reference to it (WPF uses weak listeners), do I need to unsubscribe from the object in this case? Of course, I should and it’s simple enough to do so in the setter, but do I really need to?
public class MyViewModel : INotifyPropertyChanged
{
private DataType myData;
public DataType MyData
{
get { return myData; }
protected set
{
if (value == myData)
return;
if (myData != null)
myData.PropertyChanged -= DataPropertyChanged;
myData = value;
myData.PropertyChanged += DataPropertyChanged;
OnNotifyPropertyChanged("MyData");
}
}
public void UpdateData ()
{
MyData = service.GetData();
}
// ...
}