What I want to do is ensure that if the only reference to my observer is the observable, it get\'s garbage collected and stops receiving messages.
Say I have a control w
There is another option using the weak-event-patterns
Essentially System.Windows.WeakEventManager
has you covered.
Using MVVM when your ViewModel relies on services with events you can weakly subscribe to those services allowing your ViewModel to be collected with the view without the event subscription keeping it alive.
using System;
using System.Windows;
class LongLivingSubject
{
public event EventHandler Notifications = delegate { };
}
class ShortLivingObserver
{
public ShortLivingObserver(LongLivingSubject subject)
{
WeakEventManager
.AddHandler(subject, nameof(subject.Notifications), Subject_Notifications);
}
private void Subject_Notifications(object sender, EventArgs e)
{
}
}