示例#1
0
 public bool RegisterSelector <TReturn>(string name, Func <TState, TReturn> selector, SelectorCallback <TReturn> valueChangedCallback)
 {
     return(Selectors <TReturn> .RegisterSelector(this, name, selector, valueChangedCallback));
 }
示例#2
0
 public StoreBuilder <TState> WithSelector <TReturn>(string name, Func <TState, TReturn> selector, SelectorCallback <TReturn> valueChangedCallback)
 {
     store.RegisterSelector(name, selector, valueChangedCallback);
     return(this);
 }
示例#3
0
            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);
            }