Last active
December 29, 2015 18:18
-
-
Save gbabiars/2006e5a5b87c34ba583f to your computer and use it in GitHub Desktop.
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
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