Last active
May 13, 2018 14:01
-
-
Save tomkis/541e8eced1965926d151 to your computer and use it in GitHub Desktop.
rxjs-saga.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
import { createStore, applyMiddleware } from 'redux'; | |
import { Observable, Subject } from 'rxjs'; | |
const api = (url, fail) => { | |
console.log(`Loading API ${url}`); | |
return new Promise((res, rej) => setTimeout(() => fail ? rej(`data-${url}`) : res('SUCCESS'), 1000)); | |
}; | |
const customSaga = iterable => | |
iterable | |
.filter(action => action.type === 'LOAD_API' || action.type === 'LOAD_API_FAIL') | |
.flatMap(({ type, payload }) => Observable | |
.fromPromise(api(payload, type === 'LOAD_API_FAIL')) | |
.map(response => ({type: 'DATA_LOADED', response})) | |
.catch(reason => Observable.of({type: 'DATA_LOADING_FAILED', reason}))); | |
const sagaMiddleware = saga => { | |
const subject = new Subject(); | |
return store => { | |
saga(subject).subscribe(dispatchable => store.dispatch(dispatchable)); | |
return next => action => { | |
next(action); | |
subject.next(action, store.getState()); | |
}; | |
}; | |
}; | |
const storeFactory = applyMiddleware(sagaMiddleware(customSaga))(createStore); | |
const store = storeFactory((appState, action) => { | |
console.log(action); | |
return appState; | |
}); | |
store.dispatch({type: 'LOAD_API', payload: 'Foo'}); | |
store.dispatch({type: 'LOAD_API_FAIL', payload: 'Bar'}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@tomkis1 This a great start. How are you handling subscriptions?