- Notifications
You must be signed in to change notification settings - Fork20
Simple Stupid Redux Store using Reactive Extensions
License
Odonno/ReduxSimple
Folders and files
| Name | Name | Last commit message | Last commit date | |
|---|---|---|---|---|
Repository files navigation
| Package | Versions |
|---|---|
| ReduxSimple | |
| ReduxSimple.Entity | |
| ReduxSimple.Uwp.RouterStore | |
| ReduxSimple.Uwp.DevTools |
Simple Stupid Redux Store using Reactive Extensions
Redux Simple is a .NET library based onRedux principle. Redux Simple is written with Rx.NET and built with the minimum of code you need to scale your whatever .NET application you want to design.
There is a sample UWP application to show how ReduxSimple library can be used and the steps required to make a C#/XAML application using the Redux pattern.
You can follow this link:https://www.microsoft.com/store/apps/9PDBXGFZCVMS
Like the original Redux library, you will have to initialize a newState when creating aStore + you will createReducer functions each linked to anAction which will possibly update thisState.
In your app, you can:
DispatchnewActionto change theState- and listen to events/changes using the
Subscribemethod
You will need to follow the following steps to create your own Redux Store:
- Create
Statedefinition
publicclassRootState{publicstringCurrentPage{get;set;}=string.Empty;publicImmutableArray<string>Pages{get;set;}=ImmutableArray<string>.Empty;}
Each State should immutable. That's why we prefer to use immutable types for each property of the State.
- Create
Actiondefinitions
publicclassNavigateAction{publicstringPageName{get;set;}}publicclassGoBackAction{}publicclassResetAction{}
- Create
Reducerfunctions
publicstaticclassReducers{publicstaticIEnumerable<On<RootState>>CreateReducers(){returnnewList<On<RootState>>{On<NavigateAction,RootState>((state,action)=>state.With(new{Pages=state.Pages.Add(action.PageName)})),On<GoBackAction,RootState>( state=>{varnewPages=state.Pages.RemoveAt(state.Pages.Length-1);returnstate.With(new{CurrentPage=newPages.LastOrDefault(),Pages=newPages});}),On<ResetAction,RootState>( state=>state.With(new{CurrentPage=string.Empty,Pages=ImmutableArray<string>.Empty}))};}}
- Create a new instance of your Store
sealedpartialclassApp{publicstaticreadonlyReduxStore<RootState>Store;staticApp(){Store=newReduxStore<RootState>(CreateReducers());}}
- And be ready to use your store inside your entire application...
Dispatch & Subscribe
You can now dispatch new actions using your globally accessibleStore.
usingstaticMyApp.App;// static reference on top of your fileStore.Dispatch(newNavigateAction{PageName="Page1"});Store.Dispatch(newNavigateAction{PageName="Page2"});Store.Dispatch(newGoBackAction());
And subscribe to either state changes or actions raised.
usingstaticMyApp.App;// static reference on top of your fileStore.ObserveAction<NavigateAction>().Subscribe(_=>{// TODO : Handle navigation});Store.Select(state=>state.CurrentPage).Where(currentPage=>currentPage==nameof(Page1)).Subscribe(_=>{// TODO : Handle event when the current page is now "Page1"});
Reducers
Reducers are pure functions used to create a newstate once anaction is triggered.
You can define a list ofOn functions where at least one action can be triggered.
returnnewList<On<RootState>>{On<NavigateAction,RootState>((state,action)=>state.With(new{Pages=state.Pages.Add(action.PageName)})),On<GoBackAction,RootState>( state=>{varnewPages=state.Pages.RemoveAt(state.Pages.Length-1);returnstate.With(new{CurrentPage=newPages.LastOrDefault(),Pages=newPages});}),On<ResetAction,RootState>( state=>state.With(new{CurrentPage=string.Empty,Pages=ImmutableArray<string>.Empty}))};
Sub-reducers also known as feature reducers are nested reducers that are used to update a part of the state. They are mainly used in larger applications to split state and reducer logic in multiple parts.
TheCreateSubReducers function takes a list of sub-reducers and the select feature function that returns the state property to use to save the state.
publicstaticIEnumerable<On<RootState>>CreateReducers(){varcounterReducers=Counter.Reducers.CreateReducers();varticTacToeReducers=TicTacToe.Reducers.CreateReducers();vartodoListReducers=TodoList.Reducers.CreateReducers();varpokedexReducers=Pokedex.Reducers.CreateReducers();returnCreateSubReducers(counterReducers.ToArray(),SelectCounterState).Concat(CreateSubReducers(ticTacToeReducers.ToArray(),SelectTicTacToeState)).Concat(CreateSubReducers(todoListReducers.ToArray(),SelectTodoListState)).Concat(CreateSubReducers(pokedexReducers.ToArray(),SelectPokedexState));}
Selectors
Based on what you need, you can observe the entire state or just a part of it.
Note that every selector is amemoized selector by design, which means that a next value will only be subscribed if there is a difference with the previous value.
Store.Select().Subscribe(state=>{// Listening to the full state (when any property changes)});
You can use functions to select a part of the state, like this:
Store.Select(state=>state.CurrentPage).Subscribe(currentPage=>{// Listening to the "CurrentPage" property of the state (when only this property changes)});
Simple selectors are like functions but the main benefits are that they can be reused in multiple components and they can be reused to create other selectors.
publicstaticISelectorWithoutProps<RootState,string>SelectCurrentPage=CreateSelector((RootStatestate)=>state.CurrentPage);publicstaticISelectorWithoutProps<RootState,ImmutableArray<string>>SelectPages=CreateSelector((RootStatestate)=>state.Pages);Store.Select(SelectCurrentPage).Subscribe(currentPage=>{// Listening to the "CurrentPage" property of the state (when only this property changes)});
Note that you can combine multiple selectors to create a new one.
publicstaticISelectorWithoutProps<RootState,bool>SelectHasPreviousPage=CreateSelector(SelectPages,(ImmutableArray<string>pages)=>pages.Count()>1);
You can also use variables out of the store to create a new selector.
publicstaticISelectorWithProps<RootState,string,bool>SelectIsPageSelected=CreateSelector(SelectCurrentPage,(stringcurrentPage,stringselectedPage)=>currentPage==selectedPage);
And then use it this way:
Store.Select(SelectIsPageSelected,"mainPage").Subscribe(isMainPageSelected=>{// TODO});
Sometimes, you need to consume multiple selectors. In some cases, you just want to combine them. This is what you can do withCombineSelectors function. It usesCombineLatest operator of the Rx.NET library. Here is an example:
Store.Select(CombineSelectors(SelectGameEnded,SelectWinner)).Subscribe(x=>{var(gameEnded,winner)=x;// TODO});
Effects - Asynchronous Actions
Side effects are functions that runs outside of the predictable State -> UI cycle. Effects does not interfere with the UI directly and can dispatch a new action in theReduxStore when necessary.
When you work with asynchronous tasks (side effects), you can follow the following rule:
- Create 3 actions - a start action, a
fulfilledaction and afailedaction - Reduce/Handle response on
fulfilledaction - Reduce/Handle error on
failedaction
Here is a concrete example.
publicclassGetTodosAction{}publicclassGetTodosFulfilledAction{publicImmutableList<Todo>Todos{get;set;}}publicclassGetTodosFailedAction{publicintStatusCode{get;set;}publicstringReason{get;set;}}
Store.Dispatch(newGetTodosAction());
You now need to observe this action and execute an HTTP call that will then dispatch the result to the store.
publicstaticEffect<RootState>GetTodos=CreateEffect<RootState>(()=>Store.ObserveAction<GetTodosAction>().Select(_=>_todoApi.GetTodos()).Switch().Select(todos=>{returnnewGetTodosFulfilledAction{Todos=todos.ToImmutableList()};}).Catch(e=>{returnObservable.Return(newGetTodosFailedAction{StatusCode=e.StatusCode,Reason=e.Reason});}),true// indicates if the ouput of the effect should be dispatched to the store);
And remember to always register your effect to the store.
Store.RegisterEffects(GetTodos);
Time travel
By default,ReduxStore only support the default behavior which is a forward-only state.You can however setenableTimeTravel totrue in order to debug your application with some interesting features: handlingUndo andRedo actions.
sealedpartialclassApp{publicstaticreadonlyReduxStore<RootState>Store;staticApp(){Store=newReduxStore<RootState>(CreateReducers(),true);}}
When the Store contains stored actions (ie. actions of the past), you can go back in time.
if(Store.CanUndo){Store.Undo();}
It will then fires anUndoneAction event you can subscribe to.
Store.Select().Subscribe(_=>{// TODO : Handle event when the State changed// You can observe the previous state generated or...});Store.ObserveUndoneAction().Subscribe(_=>{// TODO : Handle event when an Undo event is triggered// ...or you can observe actions undone});
Once you got back in time, you have two choices:
- Start a new timeline
- Stay on the same timeline of events
Once you dispatched a new action, the newState is updated and the previous timeline is erased from history: all previous actions are gone.
// Dispatch the next actionsStore.Dispatch(newNavigateAction{PageName="Page1"});Store.Dispatch(newNavigateAction{PageName="Page2"});if(Store.CanUndo){// Go back in time (Page 2 -> Page 1)Store.Undo();}// Dispatch a new action (Page 1 -> Page 3)Store.Dispatch(newNavigateAction{PageName="Page3"});
You can stay o nthe same timeline by dispatching the same set of actions you did previously.
// Dispatch the next actionsStore.Dispatch(newNavigateAction{PageName="Page1"});Store.Dispatch(newNavigateAction{PageName="Page2"});if(Store.CanUndo){// Go back in time (Page 2 -> Page 1)Store.Undo();}if(Store.CanRedo){// Go forward (Page 1 -> Page 2)Store.Redo();}
Reset state
You can also reset the entireStore (reset current state and list of actions) by using the following method.
Store.Reset();
You can then handle the reset event on your application.
Store.ObserveReset().Subscribe(_=>{// TODO : Handle event when the Store is reset// (example: flush navigation history and restart from login page)});
Entity management (in preview)
When dealing with entities, you often repeat the same process to add, update and remove entity from your collection state. With theReduxSimple.Entity package, you can simplify the management of entities using the following pattern:
- Start creating an
EntityStateand anEntityAdapter
publicclassTodoItemEntityState:EntityState<TodoItem,int>{}publicstaticclassEntities{publicstaticEntityAdapter<TodoItem,int>TodoItemAdapter=EntityAdapter<TodoItem,int>.Create(item=>item.Id);}
- Use the
EntityStatein your state
publicclassTodoListState{publicTodoItemEntityStateItems{get;set;}publicTodoFilterFilter{get;set;}}
- Then use the
EntityAdapterin reducers
On<CompleteTodoItemAction,TodoListState>((state,action)=>{returnstate.With(new{Items=TodoItemAdapter.UpsertOne(new{action.Id,Completed=true},state.Items)});})
- And use the
EntityAdapterin selectors
privatestaticreadonlyISelectorWithoutProps<RootState,TodoItemEntityState>SelectItemsEntityState=CreateSelector(SelectTodoListState, state=>state.Items);privatestaticreadonlyEntitySelectors<RootState,TodoItem,int>TodoItemSelectors=TodoItemAdapter.GetSelectors(SelectItemsEntityState);
publicstaticISelectorWithoutProps<RootState,List<TodoItem>>SelectItems=TodoItemSelectors.SelectEntities;
Router (in preview)
You can observe router changes in your own state. You first need to create a State which inherits fromIBaseRouterState.
publicclassRootState:IBaseRouterState{publicRouterStateRouter{get;set;}publicstaticRootStateInitialState=>newRootState{Router=RouterState.InitialState};}
In order to get router information, you need to enable the feature like this (inApp.xaml.cs):
protectedoverridevoidOnLaunched(LaunchActivatedEventArgse){// TODO : Initialize rootFrame// Enable router store featureStore.EnableRouterFeature(rootFrame);}
Redux DevTools (in preview)
Sometimes, it can be hard to debug your application. So there is a perfect tool called Redux DevTools which help you with that:
- list all dispatched actions
- payload of the action and details of the new state after dispatch
- differences between previous and next state
- replay mechanism (time travel)
In order to make the Redux DevTools work, you need to enable time travel.
publicstaticreadonlyReduxStore<RootState>Store=newReduxStore<RootState>(CreateReducers(),RootState.InitialState,true);
And then display the Redux DevTools view using a separate window.
awaitStore.OpenDevToolsAsync();
About
Simple Stupid Redux Store using Reactive Extensions
Topics
Resources
License
Contributing
Uh oh!
There was an error while loading.Please reload this page.
Stars
Watchers
Forks
Uh oh!
There was an error while loading.Please reload this page.
Contributors3
Uh oh!
There was an error while loading.Please reload this page.
