Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
public class ObservableProperty<T> : ExtendedBindableObject, IObservableObject<T>
{
readonly List<ValueObserver<T>> _subscribers = new List<ValueObserver<T>>();
T _value;
public virtual T Value
{
get
{
return _value;
}
set
{
_value = value;
RaisePropertyChanged(() => Value);
PublishValue();
}
}
public ObservableProperty()
{
}
public ObservableProperty(T defaulValue)
{
_value = defaulValue;
}
#region IObservableObject
public Guid Subscribe(Action<T> onNext)
{
if (null != _subscribers)
{
var targetObserver = new ValueObserver<T>(onNext);
_subscribers.Add(targetObserver);
onNext(_value);
return targetObserver.Owner;
}
return Guid.Empty;
}
public void Unsubscribe(Guid guid)
{
if (null != _subscribers)
{
var subscriber = _subscribers.FirstOrDefault(x => x.Owner == guid);
if(null != subscriber)
_subscribers.Remove(subscriber);
}
}
#endregion
#region Implementation
private void PublishValue()
{
foreach(var subscriber in _subscribers)
subscriber?.OnNext(_value);
}
#endregion
}
class ValueObserver<T>
{
public Action<T> OnNext { get; }
public Guid Owner { get; private set; }
public ValueObserver(Action<T> onNext)
{
OnNext = onNext;
Owner = new Guid();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.