using System.Collections.Generic; using Netcode; namespace StardewModdingAPI.Framework.StateTracking.FieldWatchers { /// A watcher which detects changes to a net list field. /// The list value type. internal class NetListWatcher : BaseDisposableWatcher, ICollectionWatcher where TValue : class, INetObject { /********* ** Fields *********/ /// The field being watched. private readonly NetList> Field; /// The pairs added since the last reset. private readonly IList AddedImpl = new List(); /// The pairs removed since the last reset. private readonly IList RemovedImpl = new List(); /********* ** Accessors *********/ /// Whether the collection changed since the last reset. public bool IsChanged => this.AddedImpl.Count > 0 || this.RemovedImpl.Count > 0; /// The values added since the last reset. public IEnumerable Added => this.AddedImpl; /// The values removed since the last reset. public IEnumerable Removed => this.RemovedImpl; /********* ** Public methods *********/ /// Construct an instance. /// The field to watch. public NetListWatcher(NetList> field) { this.Field = field; field.OnElementChanged += this.OnElementChanged; field.OnArrayReplaced += this.OnArrayReplaced; } /// Set the current value as the baseline. public void Reset() { this.AddedImpl.Clear(); this.RemovedImpl.Clear(); } /// Update the current value if needed. public void Update() { this.AssertNotDisposed(); } /// Stop watching the field and release all references. public override void Dispose() { if (!this.IsDisposed) { this.Field.OnElementChanged -= this.OnElementChanged; this.Field.OnArrayReplaced -= this.OnArrayReplaced; } base.Dispose(); } /********* ** Private methods *********/ /// A callback invoked when the value list is replaced. /// The net field whose values changed. /// The previous list of values. /// The new list of values. private void OnArrayReplaced(NetList> list, IList oldValues, IList newValues) { this.AddedImpl.Clear(); this.RemovedImpl.Clear(); foreach (TValue value in newValues) this.AddedImpl.Add(value); foreach (TValue value in oldValues) this.RemovedImpl.Add(value); } /// A callback invoked when an entry is replaced. /// The net field whose values changed. /// The list index which changed. /// The previous value. /// The new value. private void OnElementChanged(NetList> list, int index, TValue oldValue, TValue newValue) { if (newValue != null) this.AddedImpl.Add(newValue); if (oldValue != null) this.RemovedImpl.Add(oldValue); } } }