问题
I'm using Saga's takeLatest
to abort all requests except the latest. This works fine, but now I want to only abort requests which don't have identical url, params, and method.
I know Saga uses the type
attribute to compare actions (just like vanilla Redux does), but I've also added url
, params
, and method
to my actions because I was hoping there there was some way to do something like
yield takeLatestIf((action, latestAction) => {
const sameType = action.type === latestAction.type;
const sameUrl = action.url === latestAction.type;
const sameParams = areEqual(action.params, lastAction.params);
const sameMethod = action.method === lastAction.method;
return sameType && sameUrl && sameParams && sameMethod;
});
which should only abort requests if all 4 of those attribute comparisons are false.
How can I accomplish this?
回答1:
If I get it right from your question, you want this:
- Like standard
takeLatest()
. - But when a duplicate request is made, ignore it and wait for the one already executing (a reasonable use case).
So I took takeLatest()
implementation provided in the docs and adapted it to your scenario:
const takeLatestDeduped = (patternOrChannel, compareActions, saga, ...args) => fork(function*() {
let lastTask
let lastAction
while (true) {
const action = yield take(patternOrChannel)
// New logic: ignore duplicate request
if (lastTask && lastTask.isRunning() && !compareActions(lastAction, action)) {
continue
}
if (lastTask) {
yield cancel(lastTask)
}
lastTask = yield fork(saga, ...args.concat(action))
// New logic: save last action
lastAction = action
}
})
We have three cases:
- No running task: start the new one - standard behavior
- Running task, got non-duplicate: cancel old one, start new one - standard behavior
- Running task, got duplicate: ignore - new custom hehavior
So I added case #3 logic:
- Ignoring duplicate request (nothing should be done in this case, so I
continue
to handling next action). - Saving last action for future duplicate check.
来源:https://stackoverflow.com/questions/53731665/how-do-i-make-takelatest-consider-url-params-and-method