Created
December 25, 2020 13:16
-
-
Save enue/c6eab056e4554c5c35896631ca257d1a to your computer and use it in GitHub Desktop.
ReactiveDictionary.ObserveValue
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using UniRx; | |
namespace TSKT | |
{ | |
public static class ReactiveDictionaryExtentions | |
{ | |
public static ReadOnlyReactiveProperty<V> ObserveValue<K, V>(this ReactiveDictionary<K, V> dict, K key, V defaultValue = default) | |
{ | |
var comparer = EqualityComparer<K>.Default; | |
var hashCode = comparer.GetHashCode(key); | |
if (!dict.TryGetValue(key, out var current)) | |
{ | |
current = defaultValue; | |
} | |
return dict.ObserveReplace().Where(_ => comparer.GetHashCode(_.Key) == hashCode && comparer.Equals(_.Key, key)).Select(_ => _.NewValue) | |
.Merge( | |
dict.ObserveAdd().Where(_ => comparer.GetHashCode(_.Key) == hashCode && comparer.Equals(_.Key, key)).Select(_ => _.Value), | |
dict.ObserveRemove().Where(_ => comparer.GetHashCode(_.Key) == hashCode && comparer.Equals(_.Key, key)).Select(_ => defaultValue)) | |
.ToReadOnlyReactiveProperty(current); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment