Last active
March 31, 2022 15:03
-
-
Save mrpmorris/a28010e3d1e6821a91a2998779b84e5a to your computer and use it in GitHub Desktop.
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 Fluxor; | |
using Microsoft.Extensions.DependencyInjection; | |
var services = new ServiceCollection(); | |
services.AddFluxor(x => | |
{ | |
x.ScanAssemblies(typeof(Program).Assembly); | |
// PRO: No need to register lots of generic classes here | |
}); | |
var sp = services.BuildServiceProvider(); | |
var dispatcher = sp.GetRequiredService<IDispatcher>(); | |
var store = sp.GetRequiredService<IStore>(); | |
await store.InitializeAsync(); | |
dispatcher.Dispatch(new ChangeCommonState<State1>()); | |
dispatcher.Dispatch(new ChangeCommonState<State2>()); | |
dispatcher.Dispatch(new ChangeCommonState<State2>()); | |
Console.ReadLine(); | |
public record CommonState(int Counter); | |
[FeatureState] | |
public record State1 | |
{ | |
public CommonState CommonState { get; init; } = new CommonState(0); | |
} | |
[FeatureState] | |
public record State2 | |
{ | |
public CommonState CommonState { get; init; } = new CommonState(0); | |
} | |
public record ChangeCommonState<TFeatureState>(); | |
// Reducer class for State1 that uses a common CommonStateReduers.Reduce method | |
public static class State1Reducers | |
{ | |
// CON: You have to write a reducer method for the action for every feature state | |
[ReducerMethod] | |
public static State1 Reduce(State1 state, ChangeCommonState<State1> action) | |
=> | |
state with { CommonState = CommonStateReducers.Reduce(state.CommonState, action) }; | |
} | |
// Reducer class for State2 that uses a common CommonStateReduers.Reduce method | |
public static class State2Reducers | |
{ | |
// CON: You have to write a reducer method for the action for every feature state | |
[ReducerMethod] | |
public static State1 Reduce(State1 state, ChangeCommonState<State2> action) | |
=> | |
state with { CommonState = CommonStateReducers.Reduce(state.CommonState, action) }; | |
} | |
// A class that reduces actions for CommonState | |
// This is called explicitly from other reducers | |
public static class CommonStateReducers | |
{ | |
public static CommonState Reduce<TFeatureState>( | |
CommonState state, | |
ChangeCommonState<TFeatureState> action) | |
=> | |
state with { Counter = state.Counter + 1 }; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment