Creating a weak subscription to an IObservable

前端 未结 6 1337
暗喜
暗喜 2021-02-01 05:05

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

6条回答
  •  孤街浪徒
    2021-02-01 05:52

    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) 
        { 
        }
    }
    

提交回复
热议问题