Skip to content

Instantly share code, notes, and snippets.

@bfillmer
Forked from tomkis/rxjs-saga.js
Created August 5, 2016 03:06
Show Gist options
  • Save bfillmer/c7f6daa9cd51003104d633958d316f0c to your computer and use it in GitHub Desktop.
Save bfillmer/c7f6daa9cd51003104d633958d316f0c to your computer and use it in GitHub Desktop.
rxjs-saga.js
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