Last active
April 2, 2017 11:16
-
-
Save cmeeren/7343b62c8e115e646634a64fdf489ac0 to your computer and use it in GitHub Desktop.
Implementation of Redux.NET store that only surfaces the state through projections
This file contains 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
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