ObservedDictionary<TKey, TValue>

ObservedDictionary is a class that extends the IDictionary interface and allows users to subscribe to changes made to the dictionary. This can be useful in scenarios where the user wants to be notified when an item is added, removed, or updated in the dictionary.

To use ObservedDictionary, the user simply needs to create a new instance of the class and subscribe to changes using the Subscribe method. They can then make changes to the dictionary as they would with a regular Dictionary, and the subscribers will be notified of the changes.

Here is an example of how ObservedDictionary can be used:

using UnityEngine;
using Observed;

public class MyScript : MonoBehaviour
{
    private ObservedDictionary<string, int> scores;

    void Start()
    {
        scores = new ObservedDictionary<string, int>();

        // Subscribe to the dictionary's change events
        scores.Subscribe((key, value, changeType) =>
        {
            switch (changeType)
            {
                case ChangeType.Added:
                    Debug.Log($"{key} added with score {value}");
                    break;
                case ChangeType.Updated:
                    Debug.Log($"{key} updated with new score {value}");
                    break;
                case ChangeType.Removed:
                    Debug.Log($"{key} removed with score {value}");
                    break;
            }
        });

        scores.Add("player1", 100);
        // Output: player1 added with score 100
        
        scores["player1"] = 200;
        // Output: player1 updated with new score 200
        
        scores.Remove("player1");
        // Output: player1 removed with score 200
    }
}

ObservedDictionary also includes a ClearSubscriptions method which allows the user to clear all subscribers from the dictionary. This can be useful when disposing of the ObservedDictionary or when the user no longer needs to be notified of changes.

Last updated