简体   繁体   中英

How do you register/unregister handlers to the event used in Observable.FromEventPattern?

I'm getting an IObservable from Observable.FromEventPattern, as shown below:

SomeObject target = new SomeObject();
string eventName = "SomeEvent";
IObservable<T> obs = Observable.FromEventPattern<T>(target, eventName);

From what I understand, the FromEventPattern call will automatically generate add/remove event handlers for me. But when does the handler actually get added/removed?

I assume that the handler is added when the IObservable is subscribed to. Is the handler also automatically unregistered when the subscriber is disposed?

It's easy enough to just write up a simple test yourself to see when Observable uses the add/remove handlers by simply supplying your own handlers that cause side effects:

var observable = Observable.FromEvent(
    action => Console.WriteLine("Added"),
    action => Console.WriteLine("removed"));

Console.WriteLine("Subscribing");
var subscription = observable.Subscribe(unit => { });
Console.WriteLine("disposing");
subscription.Dispose();
Console.WriteLine("done");

This prints out:

Subscribing
Added
disposing
removed
done

Telling us that subscribing invokes the add handler, and disposing the subscription object removes the handler.

In the event that you have multiple subscriptions to the observable, then the handler will be added any time you subscribe to an observable that has no previous subscriptions, and disposing of a subscription only removes the handler if it was the last remaining subscriber. This can be seen by modifying the test to create multiple subscriptions and then disposing of them all.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM