Skip to content

Instantly share code, notes, and snippets.

@mrpmorris
Last active March 31, 2022 14:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mrpmorris/fb82adfe6e54017aa185b80a04120ced to your computer and use it in GitHub Desktop.
Save mrpmorris/fb82adfe6e54017aa185b80a04120ced to your computer and use it in GitHub Desktop.
State patterns in Fluxor
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