Reactive extensions handle event once

Ale*_*kov 4 event-handling system.reactive c#-4.0

If I need one handle some event I usually code like this:

            // part of browser

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

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

            view.Navigate("http://google.com");
Run Code Online (Sandbox Code Playgroud)

But as I think its not optimally and not beautiful. I know it possible to use Reactive Extensions to handle event once. How?

Eni*_*ity 6

Try this:

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

It will fire only once because of the .Take(1) and it will deal nicely with all of the attaching and detaching of the event handler.