DEV Community

Discussion on: Advanced Blazor State Management Using Fluxor, part 4 - Interactions between Features

Collapse
 
mr_eking profile image
Eric King

I believe so, yes. If you look in the Fluxor source for the Store class, you can see that when the store is dispatching an action, it first notifies each feature of the action to be processed (which does the reducing, updating State), and only afterwards does it trigger any effects (in the last line).

if (Middlewares.All(x => x.MayDispatchAction(nextActionToProcess)))
{
    ExecuteMiddlewareBeforeDispatch(nextActionToProcess);

    // Notify all features of this action
    foreach (var featureInstance in FeaturesByName.Values)
        featureInstance.ReceiveDispatchNotificationFromStore(nextActionToProcess);

    ActionSubscriber?.Notify(nextActionToProcess);
    ExecuteMiddlewareAfterDispatch(nextActionToProcess);
    TriggerEffects(nextActionToProcess);
}
Enter fullscreen mode Exit fullscreen mode

Here's the code in the Feature class that's invoking the reducers.

public virtual void ReceiveDispatchNotificationFromStore(object action)
{
    if (action is null)
        throw new ArgumentNullException(nameof(action));

    IEnumerable<IReducer<TState>> applicableReducers = Reducers.Where(x => x.ShouldReduceStateForAction(action));
    TState newState = State;
    foreach (IReducer<TState> currentReducer in applicableReducers)
    {
        newState = currentReducer.Reduce(newState, action);
    }
    State = newState;
}
Enter fullscreen mode Exit fullscreen mode
Collapse
 
bvanderpoel profile image
Bart van der Poel

Thanks for the help! Though there is no possibility of a race condition with my current implementation, the sequence and intention is not so clear. Also, the derived state is in a sense redundant, and the store should be minimal.

I found the concept of "Selectors " in Redux (note that I have lot of back-end experience with numerical solvers, but hardly any front-end, so forgive me my lack of knowledge).

Did found something like a StateSelector in Fluxor, but no documentation on it, so I created something myself:

Image description

Image description

The idea is that you supply an IState and a pure method. On any change of the base-state, the derived state will be calculated based on the supplied pure method, and anyone using this property will be notified. This seem to work beautifully.

I currently use a factory method for instantiation (called in OnInitialized), though I think this might be improved by applying attributes to these pure methods in a static class as [FluxorSelectorMethod] similarly as [ReducerMethod], and automate the rest of it via injected services and (derived) states.