Epic example with TypeScript, Redux, RxJS 6
import { ofType } from 'redux-observable'; | |
import { of } from 'rxjs'; | |
import { catchError, flatMap, map, mergeMap } from 'rxjs/operators'; | |
import UnicornActions from './unicorn.action'; | |
import UnicornApiService from './unicorn.api.service'; | |
export default class UnicornEpics { | |
public static getUnicorn = (actions$: any) => | |
actions$.pipe( | |
ofType(UnicornActions.Types.GET_UNICORN), | |
mergeMap((action: any) => | |
UnicornApiService.getUnicorn(action.id) | |
.pipe( | |
map((res: any) => UnicornActions.done(res, UnicornActions.Types.GET_UNICORN)), | |
catchError((error: any) => of(UnicornActions.error(error, UnicornActions.Types.GET_UNICORN))) | |
) | |
) | |
); | |
public static likeUnicorn = (actions$: any) => | |
actions$.pipe( | |
ofType(UnicornActions.Types.LIKE_UNICORN), | |
mergeMap((action: any) => | |
UnicornApiService.likeUnicorn(action.id) | |
.pipe( | |
flatMap((res: any) => of( | |
UnicornActions.done(res, UnicornActions.Types.LIKE_UNICORN), | |
UnicornActions.updateUnicorn(res.data.id, {color: 'rainbow'}), | |
)), | |
catchError((error: any) => of(UnicornActions.error(error, UnicornActions.Types.LIKE_UNICORN))) | |
) | |
) | |
); | |
public static updateUnicorn = (actions$: any) => | |
actions$.pipe( | |
ofType(UnicornActions.Types.UPDATE_UNICORN), | |
mergeMap((action: any) => | |
UnicornApiService.updateUnicorn(action.id, action.data) | |
.pipe( | |
map((res: any) => UnicornActions.done(res, UnicornActions.Types.UPDATE_UNICORN)), | |
catchError((error: any) => of(UnicornActions.error(error, UnicornActions.Types.UPDATE_UNICORN))) | |
) | |
) | |
); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment