Skip to content

Instantly share code, notes, and snippets.

@phdesign
Last active July 20, 2017 22:20
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 phdesign/6677a9bb337643691f9180e89b440343 to your computer and use it in GitHub Desktop.
Save phdesign/6677a9bb337643691f9180e89b440343 to your computer and use it in GitHub Desktop.
Redux.NET Middleware to persist Actions to LiteDb
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();
...
}
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