Browse Source

Merge pull request #28 from ManlyMarco/master

Added SettingChanged event to ConfigWrapper
Bepis 6 years ago
parent
commit
8671d80781
1 changed files with 30 additions and 1 deletions
  1. 30 1
      BepInEx/ConfigWrapper.cs

+ 30 - 1
BepInEx/ConfigWrapper.cs

@@ -16,6 +16,8 @@ namespace BepInEx
         private readonly Func<T, string> _objToStr;
         private readonly string _defaultStr;
         private readonly T _default;
+        private T _lastValue;
+        private bool _lastValueSet;
 
         public string Key { get; protected set; }
 
@@ -113,7 +115,13 @@ namespace BepInEx
             try
             {
                 var strVal = Config.GetEntry(Key, _defaultStr, Section);
-                return _strToObj(strVal);
+                var obj = _strToObj(strVal);
+
+                // Always update in case config was changed from outside
+                _lastValue = obj;
+                _lastValueSet = true;
+
+                return obj;
             }
             catch (Exception ex)
             {
@@ -126,8 +134,16 @@ namespace BepInEx
         {
             try
             {
+                // Always write just in case config was changed from outside
                 var strVal = _objToStr(value);
                 Config.SetEntry(Key, strVal, Section);
+
+                if (_lastValueSet && Equals(_lastValue, value)) return;
+
+                _lastValue = value;
+                _lastValueSet = true;
+
+                OnSettingChanged();
             }
             catch (Exception ex)
             {
@@ -138,6 +154,19 @@ namespace BepInEx
         public void Clear()
         {
             Config.UnsetEntry(Key, Section);
+
+            _lastValueSet = false;
+            OnSettingChanged();
+        }
+
+        /// <summary>
+        /// Fired when the setting is changed. Does not detect changes made outside from this object.
+        /// </summary>
+        public event EventHandler SettingChanged;
+
+        private void OnSettingChanged()
+        {
+            SettingChanged?.Invoke(this, EventArgs.Empty);
         }
     }
 }