c# - Rx - 取消订阅事件

标签 c# system.reactive

我有一个 INotifyPropertyChanged 对象,Foo。我使用 Rx 的 FromEvent 方法将 Foo 变成一个可观察的事件流:

var myFoo = new Foo();
var eventStream = Observable.FromEvent<PropertyChangedEventArgs>(myFoo, "PropertyChanged");

现在我想监听一个特定属性的变化,如果 .Progress == 100,取消订阅:

eventStream
   .Where(e => myFoo.Progress == 100)
   .Subscribe(OnFooFinished);

当 Progress == 100 时如何取消订阅?如果我在 .Where 子句之后添加一个 .Take(1) 调用,它会自动取消订阅吗?

最佳答案

一种选择是使用订阅的返回值:

IDisposable subscription = eventStream.Where(e => myFoo.Progress == 100)
                                      .Subscribe(OnFooFinished);

...

// Unsubscribe
subscription.Dispose();

怀疑虽然使用Take(1)确实会取消订阅,但它可能对您来说更简洁。稍微看了一下,我很确定这取消订阅,因为它会触发“完成”消息,该消息通常会自动取消订阅。恐怕我现在没有时间确认这一点:(

关于c# - Rx - 取消订阅事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3449834/

相关文章:

C#- Selenium : StaleElementReferenceException on any element on any webpage after refresh or page change

c# - 类似资源管理器的图像浏览器的最佳控件

wpf - 为什么 Observable.range 在 GUI 线程上运行时会卡住?

system.reactive - 使用 rx 在随机时间间隔生成数字

c# - 在 react 性管道中执行TPL代码并通过测试计划程序控制执行

C# ssh.net 库,cd 命令不起作用(无法发送 "/")

c# - C#中的默认继承类型

c# - 查看asp.net mvc和asp.net core mvc的目录编译时间差异

system.reactive - 使用 Rx Repeat() 和 Replay() 来缓存和重启 DNS 查询

c# - 订阅 ObservableCollection 项目属性已更改 - WPF