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
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();
}
}
}