From 4e53998a6941c45772d68d61908aea5c6fa92a6c Mon Sep 17 00:00:00 2001 From: Daniil Korostelev Date: Thu, 20 Jun 2024 09:53:14 +0200 Subject: [PATCH] add observable dictionary docs page --- docs/articles/collections-dict.md | 43 ++++++++++++++++++++++++++++++- docs/articles/collections-list.md | 2 +- 2 files changed, 43 insertions(+), 2 deletions(-) diff --git a/docs/articles/collections-dict.md b/docs/articles/collections-dict.md index 028bc69..0b9a63d 100644 --- a/docs/articles/collections-dict.md +++ b/docs/articles/collections-dict.md @@ -1,3 +1,44 @@ # Observable Dictionary -> TODO: document +`ObservableDictionary` is an observable wrapper around the standard `Dictionary`, providing the same API for managing the collection. + +In addition to the standard dictionary methods, it provides the [`Observe`](xref:TinkState.ObservableDictionary`2.Observe) method to expose itself as a read-only observable so one can bind to it and react to its changes. + +```csharp +interface ObservableDictionary : IDictionary +{ + Observable> Observe(); +} +``` + +Like most of observables, `ObservableDictionary` can be created by a static function in the `Observable` helper class: + +```csharp +static class Observable +{ + static ObservableDictionary Dictionary(); +} +``` + +Adding and removing items will naturally trigger its bindings and propagate through auto-observables. + +## Example + +```csharp +var dict = Observable.Dictionary(); +dict["a"] = 1; +dict["b"] = 2; + +var auto = Observable.Auto(() => string.Join(",", dict.Select(kvp => $"{kvp.Key}:{kvp.Value}"))); +Console.WriteLine(auto.Value); // a:1,b:2 + +// initial binding prints a:1 and b:2 +dict.Observe().Bind(readOnlyDict => +{ + foreach (var (key, value) in readOnlyDict) Console.WriteLine($"{key}:{value}"); +}); + +dict["c"] = 3; // binding prints a:1, b:2 and c:3 + +Console.WriteLine(auto.Value); // a:1,b:2,c:3 +``` diff --git a/docs/articles/collections-list.md b/docs/articles/collections-list.md index cd49f0a..40c780c 100644 --- a/docs/articles/collections-list.md +++ b/docs/articles/collections-list.md @@ -2,7 +2,7 @@ `ObservableList` is an observable wrapper around the standard `List`, providing the same API for managing the collection. -In addition to the standard list method, it provides the [`Observe`](xref:TinkState.ObservableList`1.Observe) method to expose itself +In addition to the standard list methods, it provides the [`Observe`](xref:TinkState.ObservableList`1.Observe) method to expose itself as a read-only observable so one can bind to it and react to its changes. ```csharp