Reputation: 121
I'm starting with learning how to use RxJS and I have implemented an epic with a conditional Ajax call like this:
export default (action$, store) =>
action$.ofType(GET_USERS_BY_ID)
.mergeMap((action) => {
const userIdList = action.userIdList;
let observable;
if (userIdList.length > 0) {
observable = ajax.get('api/user', { userIdList });
} else {
observable = Observable.of({
response: {}
});
}
return observable
.mergeMap((payload) => {
doSomething1(payload);
doSomething2(payload);
});
});
Is this the right way to do it, or are there some operators that simplify this?
Upvotes: 1
Views: 365
Reputation: 1899
If you only want to process actions where the userIdList has items in it, then you can filter them before making the ajax call, eg.
export default (action$, store) =>
action$.ofType(GET_USERS_BY_ID)
.filter(action => userIdList.length > 0)
.mergeMap((action) => {
const userIdList = action.userIdList;
return ajax.get('api/user', { userIdList })
.mergeMap((payload) => {
doSomething1(payload);
doSomething2(payload);
});
});
Upvotes: 1