From 07c3b58442128b1d6d38fa697958f4f8fbefac1b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C3=81d=C3=A1m=20Kov=C3=A1cs?= Date: Fri, 28 Jul 2023 17:28:13 +0200 Subject: [PATCH] Combine property WIP --- .../DeclarativeProperty/CombineProperty.cs | 44 +++++++++++++++++++ 1 file changed, 44 insertions(+) create mode 100644 src/Library/DeclarativeProperty/CombineProperty.cs diff --git a/src/Library/DeclarativeProperty/CombineProperty.cs b/src/Library/DeclarativeProperty/CombineProperty.cs new file mode 100644 index 0000000..6083395 --- /dev/null +++ b/src/Library/DeclarativeProperty/CombineProperty.cs @@ -0,0 +1,44 @@ +namespace DeclarativeProperty; + +public sealed class CombineProperty : DeclarativePropertyBase +{ + private readonly Func, Task> _combiner; + private readonly List> _sourceProperties = new(); + + public CombineProperty(Func, Task> combiner) + { + _combiner = combiner; + } + + public async Task AddSource(IDeclarativeProperty source) + { + if (_sourceProperties.Contains(source)) return; + _sourceProperties.Add(source); + source.Subscribe(OnSourceChanged); + + await Update(); + } + + public async Task RemoveSource(IDeclarativeProperty source) + { + _sourceProperties.Remove(source); + source.Unsubscribe(OnSourceChanged); + + await Update(); + } + + private async Task OnSourceChanged(TFrom? _, CancellationToken cancellationToken = default) + => await Update(cancellationToken); + + private async Task Update(CancellationToken cancellationToken = default) + { + var result = await _combiner( + _sourceProperties + .Select(p => p.Value) + .ToList() + .AsReadOnly() + ); + + await SetNewValueAsync(result, cancellationToken); + } +} \ No newline at end of file