Home > other >  Using System.Reactive with events
Using System.Reactive with events

Time:03-07

I am developing a WPF application. User can change their Address in a form. I want to raise an event when user clicks a button (to change their address) and use the UserInfoEventArgs to process some information. I am trying to use Reactive Extensions.

MS Documentation (Subject<T> constructor)

I have two doubts. How to subscribe to mySubject and also how to add the UserInfoEventArgs to the subject.

Subject<string[]> mySubject = new Subject<string[]>();

// How to subscribe to mySubject and use the method "AddressSubscriber" as the subscriber?

private void UserDataChangedHandler (object sender, UserInfoEventArgs info)
{
    string[] updatedAddress = info.NewAddress.ToArray();  

    if (updatedAddress.Any())
    {
        // How to add "updatedAddress" to mySubject so that "AddressSubscriber" can use it?
    }
}

private void AddressSubscriber(string[] adrs)
{ 
    // Do some operations with adrs
}

CodePudding user response:

How to subscribe to mySubject and use the method AddressSubscriber as the subscriber?

mySubject.Subscribe(adrs => AddressSubscriber(adrs));

How to add updatedAddress to mySubject so that AddressSubscriber can use it?

mySubject.OnNext(updatedAddress);

CodePudding user response:

Use the Observable.FromEventPattern method instead of creating a superfluous Subject<T>:

Observable.FromEventPattern<RoutedEventHandler, RoutedEventArgs>(
    h => btn.Click  = h,
    h => btn.Click -= h)
        .Select(_ => new UserInfoEventArgs())
        .Subscribe(args => { /* do something with the args...*/ });
  • Related