Created
November 11, 2017 02:03
-
-
Save abiodun0/a9166d0687fc319d5362f8c59c010ad2 to your computer and use it in GitHub Desktop.
ReduxFromRx
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
// A very simple wrapper that provides redux-like functionality using RxJS observables | |
// Redux is basically just an observable(subject), except that it's not generic enough to be used like one. | |
// By using RxJS observables, you can solve many of the problems that redux has, such as asynchronous effects, | |
// in a very simple way. Since it's using an observable, it's easy to combine and compose the store with other streams | |
// like events or ajax calls. | |
// This simple wrapper provides the same functionality as redux at only 23 lines of code | |
const createStore = function(name, reducer, initialState) { | |
const storeName = 'store:'+ name | |
const stream = Rx.Observable | |
.fromEvent(document, storeName) | |
.scan(function(state, event) { | |
return reducer(state, event.detail) | |
}, initialState) | |
const subscribe = function(callback) { | |
stream.subscribeOnNext(callback) | |
} | |
const dispatch = function(action) { | |
document.dispatchEvent(new CustomEvent(storeName, { detail: action })) | |
} | |
return { | |
stream: stream, | |
subscribe: subscribe, | |
dispatch: dispatch | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment