Last active
March 31, 2022 14:48
-
-
Save mrpmorris/fb82adfe6e54017aa185b80a04120ced to your computer and use it in GitHub Desktop.
State patterns in Fluxor
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); | |
// CON: Need to explicitly register a reducer type for each feature state | |
x.ScanTypes( | |
typeof(ChangeCommonStateReducers<State1>), // Register this generic class | |
typeof(ChangeCommonStateReducers<State2>)); // Register this generic class | |
}); | |
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.WriteLine("Done"); | |
Console.ReadLine(); | |
public interface ICommonStateOwner<TFeatureState> | |
{ | |
CommonState CommonState { get; } | |
TFeatureState WithNewCommonState(CommonState newState); | |
} | |
public record CommonState(int Counter); | |
[FeatureState] | |
public record State1 : ICommonStateOwner<State1> | |
{ | |
public CommonState CommonState { get; init; } = new CommonState(0); | |
// CON: Need to implement a method on the state class | |
public State1 WithNewCommonState(CommonState newState) => | |
this with { CommonState = newState }; | |
} | |
[FeatureState] | |
public record State2 : ICommonStateOwner<State2> | |
{ | |
public CommonState CommonState { get; init; } = new CommonState(0); | |
// CON: Need to implement a method on the state class | |
public State2 WithNewCommonState(CommonState newState) => | |
this with { CommonState = newState }; | |
} | |
public record ChangeCommonState<TFeatureState>(); | |
// PRO: This will be called automatically | |
public static class ChangeCommonStateReducers<TFeatureState> | |
where TFeatureState : ICommonStateOwner<TFeatureState> | |
{ | |
[ReducerMethod] | |
public static TFeatureState Reduce( | |
TFeatureState state, ChangeCommonState<TFeatureState> action) | |
=> | |
state.WithNewCommonState(state.CommonState with { Counter = state.CommonState.Counter + 1 }); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment