Reputation: 2028
Attempting to use RX with events, but this one is alluding me. This is the "normal" way to subscribe to an event
this.Loaded += new RoutedEventHandler(SelectPartyPersonDataEntry_Loaded);
The RX Way....
Observable.FromEventPattern<RoutedEventArgs>(this, "Loaded").Subscribe((routedEvent) => this.Searchbutton_Click(routedEvent.Sender, routedEvent.EventArgs));
however, it fails silently and I'm not sure why.
Thanks!
I'm not quite sure how to handle this, as both of these answers helped me understand where I was going wrong with this. The correct syntax (or that one that works is):
Observable.FromEventPattern<RoutedEventHandler, RoutedEventArgs>(h => this.Loaded += h, h => this.Loaded -= h).Subscribe(routedEvents => SelectPartyPersonDataEntry_Loaded(routedEvents.Sender, routedEvents.EventArgs));
Which simply looks more confusing that anything else. I have to provide both the EventHandler type (RoutedEventHandler), as well as the event argument type to (RoutedEventArgs), in order to subscribe to the events. Using this signature of the FromEventPattern means that I have to have use the +=/-= syntax subscribing to the event.
I only see one reason why you would do this over the traditional (and more concise) syntax - the difference between a strong reference, and a weak reference. If this View goes out of scope, you must ensure the strong reference in order for the view to be garbadge collected (GC). The RX syntax is a weak reference, and as such will be GC without the dereferencing the event.
Upvotes: 1
Views: 877
Reputation: 117175
I suspect that it has something to do with not providing the type of the event args. The method signature that you're using is:
IObservable<EventPattern<EventArgs>>
FromEventPattern(object target, string eventName)
I suspect you need:
IObservable<EventPattern<TEventArgs>>
FromEventPattern<TEventArgs>(object target, string eventName)
where TEventArgs: EventArgs
Better yet, don't use the "reflection" method (i.e. no magic strings). Use this instead:
IObservable<EventPattern<TEventArgs>>
FromEventPattern<TDelegate, TEventArgs>(
Action<TDelegate> addHandler, Action<TDelegate> removeHandler)
where TEventArgs: EventArgs
Upvotes: 1
Reputation: 60061
I just tested this in a WPF app:
var loadedEvent = Observable.FromEventPattern(this, "Loaded");
loadedEvent.Subscribe(e => MessageBox.Show("loaded"));
And it works; the message box is shown.
Perhaps you could elaborate what you mean when you say it fails silently -- have you tried this in a debugger? Are you sure there's a Loaded event in there?
Upvotes: 3