Creating a weak subscription to an IObservable

前端 未结 6 1349
暗喜
暗喜 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:50

    You can subscribe a proxy observer to the observable that holds a weak reference to the actual observer and disposes the subscription when the actual observer is no longer alive:

    static IDisposable WeakSubscribe(
        this IObservable observable, IObserver observer)
    {
        return new WeakSubscription(observable, observer);
    }
    
    class WeakSubscription : IDisposable, IObserver
    {
        private readonly WeakReference reference;
        private readonly IDisposable subscription;
        private bool disposed;
    
        public WeakSubscription(IObservable observable, IObserver observer)
        {
            this.reference = new WeakReference(observer);
            this.subscription = observable.Subscribe(this);
        }
    
        void IObserver.OnCompleted()
        {
            var observer = (IObserver)this.reference.Target;
            if (observer != null) observer.OnCompleted();
            else this.Dispose();
        }
    
        void IObserver.OnError(Exception error)
        {
            var observer = (IObserver)this.reference.Target;
            if (observer != null) observer.OnError(error);
            else this.Dispose();
        }
    
        void IObserver.OnNext(T value)
        {
            var observer = (IObserver)this.reference.Target;
            if (observer != null) observer.OnNext(value);
            else this.Dispose();
        }
    
        public void Dispose()
        {
            if (!this.disposed)
            {
                this.disposed = true;
                this.subscription.Dispose();
            }
        }
    }
    

提交回复
热议问题