Skip to content

Instantly share code, notes, and snippets.

@mrpmorris
Last active March 31, 2022 15:03
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/a28010e3d1e6821a91a2998779b84e5a to your computer and use it in GitHub Desktop.
Save mrpmorris/a28010e3d1e6821a91a2998779b84e5a to your computer and use it in GitHub Desktop.
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