Skip to content

Instantly share code, notes, and snippets.

@TracyNgot
Last active September 21, 2018 00:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save TracyNgot/5ad8a19c18e4c17142f4a816f77a01ed to your computer and use it in GitHub Desktop.
Save TracyNgot/5ad8a19c18e4c17142f4a816f77a01ed to your computer and use it in GitHub Desktop.
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