'Using System.Reactive with events
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
}
Solution 1:[1]
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...*/ });
Solution 2:[2]
How to subscribe to
mySubjectand use the methodAddressSubscriberas the subscriber?
mySubject.Subscribe(adrs => AddressSubscriber(adrs));
How to add
updatedAddresstomySubjectso thatAddressSubscribercan use it?
mySubject.OnNext(updatedAddress);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | mm8 |
| Solution 2 | Theodor Zoulias |
