# ObservableCollections [![GitHub Actions](https://github.com/Cysharp/ObservableCollections/workflows/Build-Debug/badge.svg)](https://github.com/Cysharp/ObservableCollections/actions) [![Releases](https://img.shields.io/github/release/Cysharp/ObservableCollections.svg)](https://github.com/Cysharp/ObservableCollections/releases) ObservableCollections is a high performance observable collections(`ObservableList`, `ObservableDictionary`, `ObservableHashSet`, `ObservableQueue`, `ObservableStack`, `ObservableRingBuffer`, `ObservableFixedSizeRingBuffer`) with synchronized views. .NET has [`ObservableCollection`](https://docs.microsoft.com/en-us/dotnet/api/system.collections.objectmodel.observablecollection-1), however it has many lacks of features. It based `INotifyCollectionChanged`, `NotifyCollectionChangedEventHandler` and `NotifyCollectionChangedEventArgs`. There are no generics so everything boxed, allocate memory every time. Also `NotifyCollectionChangedEventArgs` holds all values to `IList` even if it is single value, this also causes allocations. `ObservableCollection` has no Range feature so a lot of wastage occurs when adding multiple values, because it is a single value notification. Also, it is not thread-safe is hard to do linkage with the notifier. ObservableCollections introduces generics version of `NotifyCollectionChangedEventHandler` and `NotifyCollectionChangedEventArgs`, it using latest C# features(`in`, `readonly ref struct`, `ReadOnlySpan`). ```csharp public delegate void NotifyCollectionChangedEventHandler(in NotifyCollectionChangedEventArgs e); public readonly ref struct NotifyCollectionChangedEventArgs { public readonly NotifyCollectionChangedAction Action; public readonly bool IsSingleItem; public readonly T NewItem; public readonly T OldItem; public readonly ReadOnlySpan NewItems; public readonly ReadOnlySpan OldItems; public readonly int NewStartingIndex; public readonly int OldStartingIndex; } ``` Also, use the interface `IObservableCollection` instead of `INotifyCollectionChanged`. This is guaranteed to be thread-safe and can produce a View that is fully synchronized with the collection. ```csharp public interface IObservableCollection : IReadOnlyCollection { event NotifyCollectionChangedEventHandler CollectionChanged; object SyncRoot { get; } ISynchronizedView CreateView(Func transform, bool reverse = false); } // also exists SortedView public static ISynchronizedView CreateSortedView(this IObservableCollection source, Func identitySelector, Func transform, IComparer comparer); public static ISynchronizedView CreateSortedView(this IObservableCollection source, Func identitySelector, Func transform, IComparer viewComparer); ``` SynchronizedView helps to separate between Model and View (ViewModel). We will use ObservableCollections as the Model and generate SynchronizedView as the View (ViewModel). This architecture can be applied not only to WPF, but also to Blazor, Unity, etc. ![image](https://user-images.githubusercontent.com/46207/131979264-2463403b-0fba-474b-8f49-277c2abe1b05.png) ObservableCollections has not just a simple list, there are many more data structures. `ObservableList`, `ObservableDictionary`, `ObservableHashSet`, `ObservableQueue`, `ObservableStack`, `ObservableRingBuffer`, `ObservableFixedSizeRingBuffer`. `RingBuffer`, especially `FixedSizeRingBuffer`, can be achieved with efficient performance when there is rotation (e.g., displaying up to 1000 logs, where old ones are deleted when new ones are added). Of course, the AddRange allows for efficient batch processing of large numbers of additions. Getting Started --- For .NET, use NuGet. For Unity, please read [Unity](#unity) section. PM> Install-Package [ObservableCollections](https://www.nuget.org/packages/ObservableCollections) create new `ObservableList`, `ObservableDictionary`, `ObservableHashSet`, `ObservableQueue`, `ObservableStack`, `ObservableRingBuffer`, `ObservableFixedSizeRingBuffer`. ```csharp // Basic sample, use like ObservableCollection. // CollectionChanged observes all collection modification var list = new ObservableList(); list.CollectionChanged += List_CollectionChanged; list.Add(10); list.Add(20); list.AddRange(new[] { 10, 20, 30 }); static void List_CollectionChanged(in NotifyCollectionChangedEventArgs e) { switch (e.Action) { case NotifyCollectionChangedAction.Add: if (e.IsSingleItem) { Console.WriteLine(e.NewItem); } else { foreach (var item in e.NewItems) { Console.WriteLine(item); } } break; // Remove, Replace, Move, Reset default: break; } } ``` Handling All CollectionChanged event manually is difficult. ObservableCollections has SynchronizedView that transform element for view. ```csharp var list = new ObservableList(); var view = list.CreateView(x => x.ToString() + "$"); list.Add(10); list.Add(20); list.AddRange(new[] { 30, 40, 50 }); list[1] = 60; list.RemoveAt(3); foreach (var (_, v) in view) { // 10$, 60$, 30$, 50$ Console.WriteLine(v); } // Dispose view is unsubscribe collection changed event. view.Dispose(); ``` Blazor --- ```csharp public partial class DataTable : ComponentBase, IDisposable { [Parameter, EditorRequired] public IReadOnlyList Items { get; set; } = default!; [Parameter, EditorRequired] public Func DataTemplate { get; set; } ISynchronizedView view = default!; protected override void OnInitialized() { // TODO: CreateSortedView if (Items is IObservableCollection observableCollection) { view = observableCollection.CreateView(DataTemplate); } else { var freezedList = new FreezedList(Items); view = freezedList.CreateView(DataTemplate); } view.CollectionStateChanged += async _ => { await InvokeAsync(StateHasChanged); }; } public void Dispose() { // unsubscribe. view.Dispose(); } } // .razor, iterate view @foreach (var (row, cells) in view) { @foreach (var item in cells) { } } ``` WPF --- ```csharp // WPF simple sample. ObservableList list; public ISynchronizedView ItemsView { get; set; } public MainWindow() { InitializeComponent(); this.DataContext = this; list = new ObservableList(); ItemsView = list.CreateSortedView(x => x, x => x, comparer: Comparer.Default).WithINotifyCollectionChanged(); BindingOperations.EnableCollectionSynchronization(ItemsView, new object()); // for ui synchronization safety of viewmodel } protected override void OnClosed(EventArgs e) { ItemsView.Dispose(); } ``` Unity --- ```csharp // Unity, with filter sample. public class SampleScript : MonoBehaviour { public Button prefab; public GameObject root; ObservableRingBuffer collection; ISynchronizedView view; void Start() { collection = new ObservableRingBuffer(); view = collection.CreateView(x => { var item = GameObject.Instantiate(prefab); item.GetComponentInChildren().text = x.ToString(); return item.gameObject; }); view.AttachFilter(new GameObjectFilter(root)); } void OnDestroy() { view.Dispose(); } public class GameObjectFilter : ISynchronizedViewFilter { readonly GameObject root; public GameObjectFilter(GameObject root) { this.root = root; } public void OnCollectionChanged(ChangedKind changedKind, int value, GameObject view, in NotifyCollectionChangedEventArgs eventArgs) { if (changedKind == ChangedKind.Add) { view.transform.SetParent(root.transform); } else if (changedKind == ChangedKind.Remove) { GameObject.Destroy(view); } } public bool IsMatch(int value, GameObject view) { return value % 2 == 0; } public void WhenTrue(int value, GameObject view) { view.SetActive(true); } public void WhenFalse(int value, GameObject view) { view.SetActive(false); } } } ``` TODO: write more usage... View/SoretedView --- Filter --- Collections --- Freezed --- License --- This library is licensed under the MIT License.