Created
June 13, 2017 08:19
-
-
Save mocheng/ac1304e61380de22045105520e6007d6 to your computer and use it in GitHub Desktop.
Implement Redux Store with Rx.js
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
'use strict'; | |
const Rx = require('rxjs'); | |
const createStore = (reducer, initialState = {}) => { | |
const action$ = new Rx.Subject(); | |
let currentState = initialState; | |
const store$ = action$.startWith(initialState).scan(reducer).do( | |
state => { | |
currentState = state; | |
} | |
).publishReplay(1).refCount(); | |
return { | |
dispatch: action => { | |
action$.next(action); | |
}, | |
getState: () => currentState, | |
subscribe: (func) => { | |
const subscription = store$.subscribe(func); | |
return subscription.dispose; | |
} | |
} | |
}; | |
const reducer = (state, action) => { | |
if (action.type === 'inc') { | |
return Object.assign({}, state, {count: state.count + 1}); | |
} else if (action.type === 'dec') { | |
return Object.assign({}, state, {count: state.count - 1}); | |
} | |
return state; | |
} | |
const store = createStore(reducer, {count: 0}); | |
store.subscribe(state => { | |
console.log('### state = ', state); | |
}); | |
store.dispatch({type: 'inc'}); | |
store.dispatch({type: 'inc'}); | |
store.dispatch({type: 'inc'}); | |
store.dispatch({type: 'dec'}); | |
store.subscribe(state => { | |
console.log('### next observer state = ', state); | |
}); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment