Last active
July 20, 2017 22:20
-
-
Save phdesign/6677a9bb337643691f9180e89b440343 to your computer and use it in GitHub Desktop.
Redux.NET Middleware to persist Actions to LiteDb
This file contains hidden or 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
public App() | |
{ | |
InitializeComponent(); | |
var dbPath = DependencyService.Get<IFileHelper>().GetLocalFilePath("todo.db"); | |
var persistActionsMiddleware = new PersistActionsMiddleware<ApplicationState>(dbPath); | |
Store = new Store<ApplicationState>( | |
Reducers.Reducers.ReduceApplication, | |
new ApplicationState(), | |
persistActionsMiddleware.CreateMiddleware()); | |
persistActionsMiddleware.ReplayHistory(); | |
... | |
} |
This file contains hidden or 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 System; | |
using LiteDB; | |
using Redux; | |
namespace TodoRedux.Middleware | |
{ | |
public class PersistActionsMiddleware<TState> | |
{ | |
private IStore<TState> _store; | |
private readonly LiteCollection<ActionHistory> _actionCollection; | |
private bool _isReplaying; | |
public PersistActionsMiddleware(String databaseName) | |
{ | |
var db = new LiteDatabase(databaseName); | |
_actionCollection = db.GetCollection<ActionHistory>("ActionHistory"); | |
} | |
public Middleware<TState> CreateMiddleware() | |
{ | |
return store => | |
{ | |
_store = store; | |
return next => action => | |
{ | |
var result = next(action); | |
if (_isReplaying) return result; | |
_actionCollection.Insert(new ActionHistory { Action = action }); | |
return result; | |
}; | |
}; | |
} | |
public void ReplayHistory() | |
{ | |
_isReplaying = true; | |
foreach (var actionHistory in _actionCollection.FindAll()) | |
{ | |
_store.Dispatch(actionHistory.Action); | |
} | |
_isReplaying = false; | |
} | |
} | |
public class ActionHistory | |
{ | |
public int Id { get; set; } | |
public IAction Action { get; set; } | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment