From c4f29bd2cfb979f0304aa987a94dee03b8e47f08 Mon Sep 17 00:00:00 2001 From: John Colvin Date: Thu, 28 Mar 2019 10:49:24 -0500 Subject: [PATCH] made 'block_reentrancy()' extension method for IProperty (blocks reentrancy in value setter) --- .../spark/core/Utility/ViewModelBase.cs | 28 +++++++++++++++++++ 1 file changed, 28 insertions(+) diff --git a/src/client/spark/core/Utility/ViewModelBase.cs b/src/client/spark/core/Utility/ViewModelBase.cs index eb801c4a2..d70855046 100644 --- a/src/client/spark/core/Utility/ViewModelBase.cs +++ b/src/client/spark/core/Utility/ViewModelBase.cs @@ -47,6 +47,34 @@ namespace mbts.ui.shell { void on_errors_changed(object sender, DataErrorsChangedEventArgs e) => o.OnNext(vm.HasErrors); }); + + public static IProperty block_reentrancy(this IProperty source) => + new GatedPropertyWrapper(source); + + /// Blocks re-entrancy in setter. + class GatedPropertyWrapper : IProperty { + bool _is_updating; + readonly IProperty _source; + + public GatedPropertyWrapper(IProperty source) => + _source = source; + + public event PropertyChange Changing { add => _source.Changing += value; remove => _source.Changing -= value; } + public event PropertyChange Changed { add => _source.Changed += value; remove => _source.Changed -= value; } + + public T Value { + get => _source.Value; + set { + if (!_is_updating) { + _is_updating = true; + _source.Value = value; + _is_updating = false; + } + } + } + + public IDisposable Subscribe(IObserver<(T oldval, T newval)> observer) => _source.Subscribe(observer); + } } public class ViewModelBase : INotifyPropertyChanged, IRaiseNotifyPropertyChanged