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 T
s 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);
}
}
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;
});
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With