From d9a9cef172be8c34b57e345732bf4e582898bcbc Mon Sep 17 00:00:00 2001 From: Jesse Plamondon-Willard Date: Mon, 30 Dec 2019 11:27:25 -0500 Subject: fix ObservableCollection watcher not handling list reset (#685) --- .../FieldWatchers/ObservableCollectionWatcher.cs | 28 ++++++++++++++++++---- 1 file changed, 24 insertions(+), 4 deletions(-) (limited to 'src/SMAPI') diff --git a/src/SMAPI/Framework/StateTracking/FieldWatchers/ObservableCollectionWatcher.cs b/src/SMAPI/Framework/StateTracking/FieldWatchers/ObservableCollectionWatcher.cs index 883b1023..c29d2783 100644 --- a/src/SMAPI/Framework/StateTracking/FieldWatchers/ObservableCollectionWatcher.cs +++ b/src/SMAPI/Framework/StateTracking/FieldWatchers/ObservableCollectionWatcher.cs @@ -21,6 +21,9 @@ namespace StardewModdingAPI.Framework.StateTracking.FieldWatchers /// The pairs removed since the last reset. private readonly List RemovedImpl = new List(); + /// The previous values as of the last update. + private readonly List PreviousValues = new List(); + /********* ** Accessors @@ -78,10 +81,27 @@ namespace StardewModdingAPI.Framework.StateTracking.FieldWatchers /// The event arguments. private void OnCollectionChanged(object sender, NotifyCollectionChangedEventArgs e) { - if (e.NewItems != null) - this.AddedImpl.AddRange(e.NewItems.Cast()); - if (e.OldItems != null) - this.RemovedImpl.AddRange(e.OldItems.Cast()); + if (e.Action == NotifyCollectionChangedAction.Reset) + { + this.RemovedImpl.AddRange(this.PreviousValues); + this.PreviousValues.Clear(); + } + else + { + TValue[] added = e.NewItems?.Cast().ToArray(); + TValue[] removed = e.OldItems?.Cast().ToArray(); + + if (removed != null) + { + this.RemovedImpl.AddRange(removed); + this.PreviousValues.RemoveRange(e.OldStartingIndex, removed.Length); + } + if (added != null) + { + this.AddedImpl.AddRange(added); + this.PreviousValues.InsertRange(e.NewStartingIndex, added); + } + } } } } -- cgit