Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
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