Last active
December 27, 2017 17:11
-
-
Save hex13/06e387d86a322d68b7485a085354c44c to your computer and use it in GitHub Desktop.
Redux-like store implemented in observables
This file contains hidden or 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
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