Search code examples
c#windows-phone-8system.reactivereactive-programming

How to add NetworkInformation.NetworkStatusChanged to a Observable FromEventPattern


I have started to learn Rx recently and tried playing with event to Rx conversion. I tried creating Network Observable in Window Phone 8 using NetworkInformation.NetworkStatusChanged event.

But when I add NetworkInformation.NetworkStatusChanged using Observable.FromEventPattern like below:

var networkInformationStatus = Observable.FromEventPattern(typeof(NetworkInformation), "NetworkStatusChanged");

networkInformationStatus.Subscribe(x => 
            {
                txtClickdata.Text = string.Format("Is internet connected: {0}", NetworkInterface.GetIsNetworkAvailable());
                txtClickdata2.Text = string.Format("Network type: {0}", NetworkInterface.NetworkInterfaceType);
            });

This is giving me following error: enter image description here

What am I doing wrong? How to add this event to Observable?


Solution

  • If you read the documentation on the method you are using it says that it is only for

    events conforming to the standard .NET event pattern with a System.EventArgs parameter

    NetworkInformation.NetworkStatusChanged is a non-standard event type so you need to use the FromEvent with the conversion overload.

            Observable.FromEvent<NetworkStatusChangedEventHandler, object>(
                emit => new NetworkStatusChangedEventHandler(
                                     (target) => emit(target)),
                h => NetworkInformation.NetworkStatusChanged += h, 
                h => NetworkInformation.NetworkStatusChanged -= h);
    

    This will allow Rx to properly convert the incoming event.