|
| 1 | +import type { AnyAction } from 'redux'; |
1 | 2 | import { takeEvery, put, spawn } from 'redux-saga/effects';
|
| 3 | + |
2 | 4 | import cancellableHandler from './utils/cancellableHandler';
|
3 | 5 |
|
4 | 6 | import type { TakeLatestRequest, RequestHandler, RequestId } from '../types';
|
5 | 7 |
|
6 |
| -export default function* takeLatestRequest( |
7 |
| - { REQUEST, cancelTask, requestIdSelector }: TakeLatestRequest, |
8 |
| - requestHandler: RequestHandler, |
| 8 | +export default function* takeLatestRequest< |
| 9 | + RequestAction extends AnyAction = AnyAction, |
| 10 | + CancelAction extends AnyAction = AnyAction, |
| 11 | +>( |
| 12 | + { REQUEST, cancelTask, requestIdSelector }: TakeLatestRequest<RequestAction, CancelAction>, |
| 13 | + requestHandler: RequestHandler<RequestAction>, |
9 | 14 | ) {
|
10 | 15 | const runningTasks = new Set<RequestId>();
|
11 | 16 | const DEFAULT_REQUEST_ID = Symbol('DEFAULT_REQUEST_ID');
|
12 | 17 |
|
13 |
| - yield takeEvery(REQUEST, function* (action) { |
| 18 | + yield takeEvery(REQUEST, function* (action: RequestAction) { |
14 | 19 | const requestId = requestIdSelector ? requestIdSelector(action) : DEFAULT_REQUEST_ID;
|
15 | 20 |
|
16 | 21 | if (runningTasks.has(requestId)) {
|
17 | 22 | yield put(cancelTask(requestId, action));
|
18 | 23 | runningTasks.delete(requestId);
|
19 | 24 | }
|
20 | 25 |
|
21 |
| - yield spawn(cancellableHandler, { |
22 |
| - handler: requestHandler, |
23 |
| - handlerArg: action, |
24 |
| - CANCEL: cancelTask(requestId, action).type, |
25 |
| - onComplete() { |
26 |
| - runningTasks.delete(requestId); |
27 |
| - }, |
| 26 | + yield spawn(function* () { |
| 27 | + yield* cancellableHandler<RequestAction, CancelAction['type']>({ |
| 28 | + handler: requestHandler, |
| 29 | + handlerArg: action, |
| 30 | + CANCEL: cancelTask(requestId, action).type, |
| 31 | + onComplete() { |
| 32 | + runningTasks.delete(requestId); |
| 33 | + }, |
| 34 | + }); |
28 | 35 | });
|
29 | 36 |
|
30 | 37 | runningTasks.add(requestId);
|
|
0 commit comments