我对Rx.Net感兴趣。并看着[https://docs.microsoft.com/en-us/previous-versions/dotnet/reactive-extensions/hh211731(v=vs.103)][1]
[1]:Observable.FromEventPattern方法。两个参数:addHandler和removeHandler使我感兴趣。我以为这两个处理程序将不会执行,它们只是伪参数,而且没有用。因此,当我如下更改代码时-将不同的处理程序绑定到按钮click事件,Observable不再触发Observer。
任何人都可以在这里解释更多的原因,为什么从未调用h(RoutedEventHandler)很重要?
public MainWindow()
{
InitializeComponent();
IObservable<EventPattern<RoutedEventArgs>> clicks = Observable.FromEventPattern<RoutedEventHandler, RoutedEventArgs>(
h => {
Console.WriteLine("AddHandler for {the second button}");
secondButton.Click += AnotherHandler;
},
h=> secondButton.Click -= AnotherHandler);
clicks.SubscribConsole("Example");
}
private void AnotherHandler(object sender, RoutedEventArgs args)
{
}
private void Button_Click(object sender, RoutedEventArgs e)
{
Console.WriteLine("Button click");
}
在下面的示例中,我有两个按钮。一种是与可观察对象绑定的“ secondButton”。另一个按钮,取消对可观察对象的订阅。
如果我单击“ secondButton”三次,然后单击“ UnsubscribeButton”,则会在控制台中显示以下输出:
Added event handler
secondButton clicked
secondButton clicked
secondButton clicked
Unsubscribe button clicked
Removed event handler
因此,您可以看到FromEvent Observable被预订时,将调用addHandler动作。现在,每次单击“ secondButton”时,可观察对象就会打勾。放置observable时,将调用removeHandler动作。
[如果我随后尝试单击'secondButton',则没有任何反应-因为它已取消订阅。
public partial class MainWindow : Window { private readonly IDisposable _subscription; public MainWindow() { InitializeComponent(); IObservable<EventPattern<RoutedEventArgs>> clicks = Observable.FromEventPattern<RoutedEventHandler, RoutedEventArgs>( h => { secondButton.Click += h; Console.WriteLine("Added event handler"); }, h => { secondButton.Click -= h; Console.WriteLine("Removed event handler"); }); _subscription = clicks.Subscribe(_ => Console.WriteLine("secondButton clicked")); } private void UnsubscribeButton_Click(object sender, RoutedEventArgs e) { // Unsubscribe by dispose Console.WriteLine("Unsubsribe button clicked"); _subscription.Dispose(); } }
顺便说一句,这样做没有意义:
Observable.FromEventPattern<RoutedEventHandler, RoutedEventArgs>(
h => secondButton.Click += AnotherHandler,
h => secondButton.Click -= AnotherHandler);
因为可观察对象将永远不会勾选任何值。您需要这样做:
Observable.FromEventPattern<RoutedEventHandler, RoutedEventArgs>(
h => secondButton.Click += h,
h => secondButton.Click -= h);