Skip to content

Instantly share code, notes, and snippets.

@hex13
Last active December 27, 2017 17:11
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 hex13/06e387d86a322d68b7485a085354c44c to your computer and use it in GitHub Desktop.
Save hex13/06e387d86a322d68b7485a085354c44c to your computer and use it in GitHub Desktop.
Redux-like store implemented in observables
import xs from 'xstream';
// If I intended to make a serious state-management system based on observables, I would probably not try to imitate Redux
// but this was made only for self-learning and for fun.
// Redux-like store factory:
const createStore = (reducer, initial) => {
const action$ = xs.create({start() {},stop() {}});
// this one line is core Redux functionality:
const state$ = action$.fold(reducer, initial);
let lastState = initial;
state$.subscribe({
next(state) {
lastState = state
}
});
return {
dispatch: action$.shamefullySendNext.bind(action$),
getState: () => lastState,
subscribe: f => {
state$.subscribe({next: f});
},
}
};
// ----------------------------------------------------------------------
// Counter hello world:
// -----------------------------------------------------------------------
const counter = (state, action) => {
switch (action.type) {
case 'inc':
return {counter: state.counter + 1}
case 'dec':
return {counter: state.counter - 1}
default:
return state;
}
};
const store = createStore(counter, {counter: 1});
store.subscribe(() => {
console.log("UPDATE", store.getState())
});
store.dispatch({type: 'inc'});
store.dispatch({type: 'inc'});
store.dispatch({type: 'inc'});
store.dispatch({type: 'dec'});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment