Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using .NET Rx to observe property changed with Action events

Say I am using the following interface (assume we can't change our implementation to make it IObservable<T> as well as IProperty<T>).

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

I am trying to observe the collection of Ts generated as the value changes. Because the event is declared as Action rather than the standard .NET event pattern I don't think I can use Observable.FromEvent(...).

I've come up with a wrapper that seems to work, but as an Rx newbie I'm sure I'm missing some built in abstractions (or am possibly just doing the whole thing wrong).

Is there any way to do this using built in Rx functionality? If not, is my wrapper missing any obvious abstractions, or is there a completely different approach I should be taking?

//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);
    }
}
like image 651
David Tchepak Avatar asked May 19 '11 08:05

David Tchepak


1 Answers

This should do it:

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;
        });
    }
}
like image 59
Scott Weinstein Avatar answered Nov 15 '22 21:11

Scott Weinstein