Epic
Epics are used for handling asynchronous side effects using RxJS or Promise.
Methods
attach(epic)
Attach a child epic.
Arguments
epic: Epic
- the epic to attach.
Returns
{Epic}
- this epic.
Example
import { Epic } from 'typeless';
import { mySubEpic } from './epics/subModule';
new Epic()
.attach(mySubEpic)
on(actionCreator, handler)
Attach a handler for the specific action creator. The action creator is a function generated by createModule
.
Arguments
actionCreator: ActionCreator
- the action creator.handler: (payload, { action$ }, action) => EpicResult
The function handler with the following parameters:payload: object
- the action payload. The type is inferred automatically from ActionCreator.deps
- contains following dependencies:action$: Observable<Action>
the Rx Observable with all actions.
action: object
- the original action.
The handler is allowed to return 5 types:
Observable<Action | Action[] | null>
- the Rx stream which containAction
orAction[]
ornull
.Promise<Action | Action[] | null>
- the Promise which containAction
orAction[]
ornull
.Action
- the action object.Action[]
- an array of actions.- null - a null value.
If handler returned
null
orObservable<null>
orPromise<null>
, nothing to do after execute.
Else, dispatch actions which returned by handler.
Returns
{Epic}
- this epic
Example
// interface.ts
import { createModule } from 'typeless';
import { UserSymbol } from './symbol';
const [handle, UserActions] = createModule(UserSymbol)
.withActions({
loadUser: (id: number) => ({ payload: { id } }),
userLoaded: (user: User) => ({ payload: { user } }),
});
// module.ts
import * as Rx from 'typeless/rx';
import { handle, UserActions } from './interface';
import { API } from '../services/API';
handle
.epic()
.on(UserActions.loadUser, ({ id }, { getState }) => {
if (getState().user.isLoaded) {
// already loaded, ignore
return null;
}
return API.loadUser(id).pipe(Rx.map(user => UserActions.userLoaded(user)));
});
onMany(actionCreators[], handler)
Attach a handler for multiple action creators. This function is very similar to on
.
Arguments
actionCreators: ActionCreator[]
- the action creators to match.handler: (payload, { action$, }, action) => EpicResult
Returns
{Epic}
- this epic.
Example
// interface.ts
import { createModule } from 'typeless';
import { UserSymbol } from './symbol';
const [handle, UserActions] = createModule(UserSymbol)
.withActions({
reloadUser: (id: number) => ({ payload: { id } }),
loadUser: (id: number) => ({ payload: { id } }),
});
// module.ts
import * as Rx from 'typeless/rx';
import { handle } from './interface';
import { API } from '../services/API';
handle
.epic()
.onMany([UserActions.loadUser, UserActions.reloadUser], ({ id }) => {
return API.loadUser(id).pipe(Rx.map(user => UserActions.userLoaded(user)));
});