Skip to content

Instantly share code, notes, and snippets.

@cmeeren
Last active April 2, 2017 11:16
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 cmeeren/7343b62c8e115e646634a64fdf489ac0 to your computer and use it in GitHub Desktop.
Save cmeeren/7343b62c8e115e646634a64fdf489ac0 to your computer and use it in GitHub Desktop.
Implementation of Redux.NET store that only surfaces the state through projections
namespace Redux
{
using System;
using System.Reactive.Linq;
using JetBrains.Annotations;
/// <summary>A wrapper for <see cref="C:Store{TState}" /> whose state is only accessible through projections.</summary>
public class ProjectingStore<TState>
{
private readonly Store<TState> store;
/// <inheritdoc cref="Store{TState}" />
public ProjectingStore(Reducer<TState> reducer, TState initialState, params Middleware<TState>[] middlewares)
{
this.store = new Store<TState>(reducer, initialState, middlewares);
}
/// <inheritdoc cref="M:Store{TState}.Dispatch" />
public IAction Dispatch(IAction action)
{
return this.store.Dispatch(action);
}
/// <summary>
/// Returns an observable of a projection of the state. Uses DistinctUntilChanged to only push elements
/// when the projection result changes.
/// </summary>
public IObservable<TProjection> Observe<TProjection>(Func<TState, TProjection> projection)
{
return this.store.Select(projection).DistinctUntilChanged();
}
/// <summary>Returns a (snapshot) projection of the current state.</summary>
[CanBeNull]
public TProjection Project<TProjection>(Func<TState, TProjection> projection)
{
return projection(this.store.GetState());
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment