Skip to content

Observed Collection

The ObservedCollection<T> class provides a generic collection that notifies its subscribers when changes occur. It is an extension of the ObservableCollection<T> class from the .NET library, offering added functionality such as the ability to handle exceptions, and allowing clients to subscribe or unsubscribe to notifications.

This class is useful in scenarios where it is crucial to be notified of changes to a collection, for example, in real-time applications or UI updates.

Properties

  • IEnumerable<T> Values: Gets or sets the values of the ObservedCollection<T>.
  • bool HandleExceptions: Gets or sets a value indicating whether exceptions should be handled internally. When set to false, exceptions will be thrown outside the class.

Methods

  • void SetSilently(IEnumerable<T> items): Sets the collection silently with the provided items without triggering notifications.
  • void Subscribe(Action<T, NotifyCollectionChangedAction> callback): Subscribes a callback to be notified when the collection changes.
  • void Unsubscribe(Action<T, NotifyCollectionChangedAction> callback): Unsubscribes a previously subscribed callback.
  • void ClearAll(): Clears the collection and sends notifications for all removed items.
  • void ClearSubscriptions(): Clears all the subscribers from the collection.
  • void NotifyChanged(NotifyCollectionChangedEventArgs e): Notifies the subscribers about the changes in the collection.
  • void NotifyChanged(T item, NotifyCollectionChangedAction changeType): Notifies the subscribers about the specified change in the collection.

Example

var myCollection = new ObservedCollection<int>();

myCollection.Subscribe((item, action) =>
{
    Debug.Log($"Item {item} was {action}");
});

myCollection.Add(1); // Output: Item 1 was Added