Skip to content

Instantly share code, notes, and snippets.

@gbabiars
Last active December 29, 2015 18:18
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 gbabiars/2006e5a5b87c34ba583f to your computer and use it in GitHub Desktop.
Save gbabiars/2006e5a5b87c34ba583f to your computer and use it in GitHub Desktop.
const createStore = (reducer, initialState) => {
let dispatcher$ = new Rx.Subject();
let state$ = new Rx.BehaviorSubject(initialState);
dispatcher$.scan(reducer, state$.getValue()).subscribe(state$);
return {
dispatch(action) {
dispatcher$.next(action);
},
subscribe(cb) {
let sub = state$.subscribe(cb);
return sub.unsubscribe.bind(sub);
},
getState() {
return state$.getValue();
}
}
};
let reducer = (state = 0, action) => {
if(action.type === 'INCREMENT') {
return state + 1;
}
if(action.type === 'DECREMENT') {
return state - 1;
}
return state;
};
let initialState = 0;
let store = createStore(reducer, initialState);
console.log(`state before sub ${store.getState()}`);
let unsub1 = store.subscribe(x => console.log(`sub1 ${x}`));
let unsub2 = store.subscribe(x => console.log(`sub2 ${x}`));
store.dispatch({ type: 'INCREMENT' });
unsub1();
unsub2();
console.log('unsub');
store.subscribe(x => console.log(`sub3 ${x}`));
store.dispatch({ type: 'INCREMENT' });
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment