How to use .NET Rx FromEvent so that add event handler is called once and remove handler is called on demand

402 views Asked by At

Is it possible to use .NET Rx Observable.FromEvent method or is there another method that allows to create an Observable from an event but calls add event handler only once when the first Subscribe method is called or when the FromEvent (or similar method) is called and don't call remove event when an Observer is unsubscribed but rather allows to remove the event manually.

I have a special situation. The library providing that event allows to add a handler or handlers only until a certain method on that object is called. After that trying to add another handler throws an exception. Thus, it seems that I cannot use FromEvent because produced Observable adds and removes event handler each time Subscribe is called and then Observer is unsubscribed.

What would be the best approach in this situation?

1

There are 1 answers

0
Timothy Shields On BEST ANSWER

Use the Publish method to get an IConnectableObservable<T>

Subscribe to this observable as many times as you want. There will only ever be one underlying subscription to the event, and subscribing and unsubscribing from this observable won't have any effects on the underlying subscription.

IConnectableObservable<T> connectableObservable = Observable.FromEvent(…).Publish();

Until you call Connect, the event will be ignored.

IDisposable connection = connectableObservable.Connect();

While the connection is active, all subscribers to the observable will receive a notification when the event fires. To unsubscribe from the underlying event, Dispose the connection.

connection.Dispose();

Now events will be ignored again.