c# - 使用 .NET Rx 观察随 Action 事件改变的属性

标签 c# .net system.reactive

假设我正在使用以下接口(interface)(假设我们不能更改我们的实现以使其成为 IObservable<T> 以及 IProperty<T>)。

public interface IProperty<T> {
    T Value { get; set; }
    event Action ValueChanged;
}

我正在尝试观察 T 的集合s 随着值的变化而生成。因为事件声明为 Action而不是标准的 .NET 事件模式,我认为我不能使用 Observable.FromEvent(...) .

我想出了一个似乎可行的包装器,但作为一个 Rx 新手,我确信我缺少一些内置的抽象(或者可能只是做错了整个事情)。

有没有办法使用内置的 Rx 功能来做到这一点?如果不是,我的包装器是否缺少任何明显的抽象,或者我是否应该采用完全不同的方法?

//Example wrapper
public class ObservableProperty<T> : IObservable<T> {
    private readonly IProperty<T> _property;
    public ObservableProperty(IProperty<T> property) { _property = property; }

    public IDisposable Subscribe(IObserver<T> observer) {
        Action action = () => observer.OnNext(_property.Value);
        _property.ValueChanged += action;
        return Disposable.Create(() => _property.ValueChanged -= action);
    }
}

最佳答案

应该这样做:

public static class RxExt
{
    public static IObservable<T> FromMyEvent<T>(this IProperty<T> src)
    {
        return System.Reactive.Linq.Observable.Create<T>((obs) =>
        {
            Action eh = () => obs.OnNext(src.Value);
            src.ValueChanged += eh;
            return () => src.ValueChanged -= eh;
        });
    }
}

关于c# - 使用 .NET Rx 观察随 Action 事件改变的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6056004/

相关文章:

c# - 如何防止点击通过控件传递到其下方的控件

c# - .NET 的 RX - 从 Disposable.Create 中调用 observer.OnCompleted 时没有任何反应

system.reactive - 我如何 DumpLive 长时间运行的进程的结果?

c# - 我如何创建一个在两个可观察对象之间交替的可观察对象

c# - Entity Framework 单个漂亮的错误消息

c# - Entity Framework 数据库表关联

c# - 条件合并同时合并两个列表的副本

c# - "Enum as immutable rich-object": is this an anti-pattern?

c# - 如何将 IQueryable 转换为 DataTable

c# - 在运行时将图像添加到 Crystal Report