Home > Net >  Watch observer's unsubscription from an observable (System.Reactive)
Watch observer's unsubscription from an observable (System.Reactive)

Time:10-18

I want to be notified (Eg. hit breakpoint) when a subscription to my observable is disposed.

Is there an easy way to do it?

CodePudding user response:

Try this extension method:

public static IObservable<T> OnUnsubscribe<T>(this IObservable<T> source, Action unsubscribe) =>
    Observable
        .Create<T>(o =>
            new CompositeDisposable(
                source.Subscribe(o),
                Disposable.Create(unsubscribe)));

Try it like this:

async Task Main()
{
    IDisposable subscription =
        Observable
            .Interval(TimeSpan.FromSeconds(1.0))
            .OnUnsubscribe(() =>
            {
                Console.WriteLine("/* break-point here */");
            })
            .Subscribe(x => Console.WriteLine(x));
            
    await Task.Delay(TimeSpan.FromSeconds(2.5));
    
    subscription.Dispose();
}

That produces:

0
1
/* break-point here */

Please note that this also fires when the observable ends naturally.

  • Related