I have a problem with redux-observables. In my situation one epic wait for ending of another epic. The second epic can make a request or return data from the cache. When second makes the request all work as expected, but when it returns cache the first one doesn't continue.
const { Observable } = Rx;
const FETCH_USER = 'FETCH_USER';
const FETCH_USER_FULFILLED = 'FETCH_USER_FULFILLED';
const FETCH_USER2 = 'FETCH_USER2';
const FETCH_USER_FULFILLED2 = 'FETCH_USER_FULFILLED2';
const FETCH_USER_REJECTED = 'FETCH_USER_REJECTED';
const FETCH_USER_CANCELLED = 'FETCH_USER_CANCELLED';
const fetchUser = id => ({ type: FETCH_USER, payload: id });
const fetchUserFulfilled = payload => ({ type: FETCH_USER_FULFILLED, payload });
const fetchUser2 = id => ({ type: FETCH_USER2, payload: id });
const fetchUserFulfilled2 = payload => ({ type: FETCH_USER_FULFILLED2, payload });
const cancelFetchUser = () => ({ type: FETCH_USER_CANCELLED });
let isFetchced = false;
const fakeAjax = url =>
Observable.of({
id: url.substring(url.lastIndexOf('/') + 1),
firstName: 'Bilbo',
lastName: 'Baggins'
}).delay(1000);
const fakeAjax2 = url =>
Observable.of({
id: url.substring(url.lastIndexOf('/2') + 1),
firstName: 'Bilbo2',
lastName: 'Baggins2'
}).delay(1000);
const fetchUserEpic = (action$, store) =>
action$.ofType(FETCH_USER)
.mergeMap(action => {
const observable = isFetchced ? Observable.of({
id: 2,
firstName: 'Bilbo',
lastName: 'Baggins'
}) : fakeAjax(`/api/users/${action.payload}`);
isFetchced = true;
console.log(action);
return observable
.map(response => fetchUserFulfilled(response))
.takeUntil(action$.ofType(FETCH_USER_CANCELLED))
});
const fetchUserEpic2 = action$ =>
action$.ofType(FETCH_USER2)
.switchMap(() => action$.ofType(FETCH_USER_FULFILLED)
.take(1)
.mergeMap(() => {
console.log("First epic");
return fakeAjax2(`/api/users/${1}`)
.map(response => fetchUserFulfilled2(response))
}).startWith(fetchUser('redux-observable')));
const users = (state = {}, action) => {
switch (action.type) {
case FETCH_USER_FULFILLED:
return {
...state,
[action.payload.id]: action.payload
};
default:
return state;
}
};
const isFetchingUser = (state = false, action) => {
switch (action.type) {
case FETCH_USER:
return true;
case FETCH_USER_FULFILLED:
case FETCH_USER_CANCELLED:
return false;
default:
return state;
}
};
Here is emulation https://jsbin.com/qitutixuqu/1/edit?html,css,js,console,output. After clicking on the button "Fetch user info" in the console you can see "First epic", after the second click on the button there is no message in console. If you add delay to
Observable.of({
id: 2,
firstName: 'Bilbo',
lastName: 'Baggins'
}).delay(10)
it starts work as expected.