public bool RegisterSelector <TReturn>(string name, Func <TState, TReturn> selector, SelectorCallback <TReturn> valueChangedCallback) { return(Selectors <TReturn> .RegisterSelector(this, name, selector, valueChangedCallback)); }
public StoreBuilder <TState> WithSelector <TReturn>(string name, Func <TState, TReturn> selector, SelectorCallback <TReturn> valueChangedCallback) { store.RegisterSelector(name, selector, valueChangedCallback); return(this); }
internal static bool RegisterSelector(Store <TState> store, string name, Func <TState, TReturn> selector, SelectorCallback <TReturn> valueChangedCallback) { if (selector == null) { return(false); } var selectorDictionary = SelectorDictionary.GetOrAdd(store, (a) => new ConcurrentDictionary <string, Func <TState, TReturn> >()); var selectorReturnValues = SelectorReturnValues.GetOrAdd(store, (a) => new ConcurrentDictionary <string, TReturn>()); selectorDictionary[name] = (state) => { try { return(selector(state)); } catch (Exception) { return(default(TReturn)); } }; selectorReturnValues[name] = selectorDictionary[name](store.State); void handler(object sender, StateChangeEventArgs <TState> eventArgs) { var newValue = selectorDictionary[name](eventArgs.NewState); var previousValue = selectorReturnValues[name]; if (!EqualityComparer <TReturn> .Default.Equals(newValue, previousValue)) { selectorReturnValues[name] = newValue; try { valueChangedCallback?.Invoke(previousValue, newValue); } catch (Exception) { valueChangedCallback = null; } } } store.StateChanged += handler; return(true); }