Skip to content

Instantly share code, notes, and snippets.

@tomkis
Last active May 13, 2018 14:01
Show Gist options
  • Save tomkis/541e8eced1965926d151 to your computer and use it in GitHub Desktop.
Save tomkis/541e8eced1965926d151 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'});
@BerkeleyTrue
Copy link

@tomkis1 This a great start. How are you handling subscriptions?

@tomkis
Copy link
Author

tomkis commented Feb 15, 2016

@BerkeleyTrue can you elaborate on this please? I am not entirely sure what you exactly mean.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment