Reactive extensions process an event once

If I need a single event, I usually do the following:

            // part of browser

            UrlEventHandler docReadyDelegate = null;
            var documentReady = new UrlEventHandler((sender, args) =>
            {
                view.DocumentReady -= docReadyDelegate; // unsubscribe
                // some code here. Fired then browser document is ready!
            });

            docReadyDelegate = documentReady;
            view.DocumentReady += docReadyDelegate; // subscribe

            view.Navigate("http://google.com");

But I think that this is not optimal and not beautiful. I know that you can use Reactive Extensions to process the event once. How?

+4
source share
1 answer

Try the following:

    Observable
        .FromEventPattern<UrlEventHandler, UrlEventArgs>(
            h => view.DocumentReady += h, 
            h => view.DocumentReady -= h)
        .Take(1)
        .Subscribe(se =>
        {
            /* code run only once */
        });

It will fire only once because of .Take(1), and it will perfectly handle all the connection and disconnection of the event handler.

+6
source

All Articles