using System.Collections.Generic; using Netcode; namespace StardewModdingAPI.Framework.StateTracking.FieldWatchers { /// A watcher which detects changes to a Netcode collection. /// The value type within the collection. internal class NetCollectionWatcher : BaseDisposableWatcher, ICollectionWatcher where TValue : class, INetObject { /********* ** Fields *********/ /// The field being watched. private readonly NetCollection Field; /// The pairs added since the last reset. private readonly List AddedImpl = new(); /// The pairs removed since the last reset. private readonly List RemovedImpl = new(); /********* ** Accessors *********/ /// public string Name { get; } /// public bool IsChanged => this.AddedImpl.Count > 0 || this.RemovedImpl.Count > 0; /// public IEnumerable Added => this.AddedImpl; /// public IEnumerable Removed => this.RemovedImpl; /********* ** Public methods *********/ /// Construct an instance. /// A name which identifies what the watcher is watching, used for troubleshooting. /// The field to watch. public NetCollectionWatcher(string name, NetCollection field) { this.Name = name; this.Field = field; field.OnValueAdded += this.OnValueAdded; field.OnValueRemoved += this.OnValueRemoved; } /// public void Update() { this.AssertNotDisposed(); } /// public void Reset() { this.AssertNotDisposed(); this.AddedImpl.Clear(); this.RemovedImpl.Clear(); } /// public override void Dispose() { if (!this.IsDisposed) { this.Field.OnValueAdded -= this.OnValueAdded; this.Field.OnValueRemoved -= this.OnValueRemoved; } base.Dispose(); } /********* ** Private methods *********/ /// A callback invoked when an entry is added to the collection. /// The added value. private void OnValueAdded(TValue value) { this.AddedImpl.Add(value); } /// A callback invoked when an entry is removed from the collection. /// The added value. private void OnValueRemoved(TValue value) { this.RemovedImpl.Add(value); } } }