Skip to content

Instantly share code, notes, and snippets.

@mocheng
Created June 13, 2017 08:19
Show Gist options
  • Save mocheng/ac1304e61380de22045105520e6007d6 to your computer and use it in GitHub Desktop.
Save mocheng/ac1304e61380de22045105520e6007d6 to your computer and use it in GitHub Desktop.
Implement Redux Store with Rx.js
'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