所以我有一个用例,我在移动 map 时更新 api 请求 - 但它可能会生成几个带有小 map 移动的快速触发请求 - 我想取消除最后一个之外的所有飞行请求。我可以使用 debounce 仅在延迟后发送请求。但是,如果它们碰巧仍在处理中,我仍然想取消任何旧请求。
const fetchNearbyStoresEpic = action$ =>
action$.ofType(FETCH_NEARBY_STORES)
.debounceTime(500)
.switchMap(action =>
db.collection('stores')
.where('location', '<=', action.payload.max).
.where('location', '>=', action.payload.min)
.map(response => fetchNearbyStoresFulfilled(response))
.takeUntil(action$.ofType(FETCH_STORES_CANCELLED))
);
我看到你可以使用
takeUntil
但您需要明确触发取消操作。我在文档中看到 switchMap 将采用最新的并取消所有其他的 - 我是否必须在我的 api 调用中实现取消接口(interface)?在这种情况下,它将是对 firestore 的 firebase 查询。
最佳答案
来自 comment I made在 GitHub 问题中:
Because they have a time dimension, there are multiple flattening strategies for observables:
- With
mergeMap
(which hasflatMap
as an alias), received observables are subscribed to concurrently and their emitted values are flattened into the output stream.- With
concatMap
, received observables are queued and are subscribed to one after the other, as each completes. (concatMap
ismergeMap
with a concurrency of one.)- With
switchMap
, when an observable is received it's subscribed to and any subscription to a previously received observable is unsubscribed.- With
exhaustMap
, when an observable is received it's subscribed to unless there is a subscription to a previously received observable and that observable has not yet completed - in which case the received observable is ignored.
所以,就像马克在他的回答中所说,当
switchMap
收到后续操作,它将取消订阅任何不完整的请求。但是,在去抖操作到达
switchMap
之前,该请求不会被取消。 .如果您想在另一次移动时立即取消任何未决请求 - 而不是等待去抖动持续时间 - 您可以使用 takeUntil
与 FETCH_NEARBY_STORES
行动:const fetchNearbyStoresEpic = action$ =>
action$.ofType(FETCH_NEARBY_STORES)
.debounceTime(500)
.switchMap(action =>
db.collection('stores')
.where('location', '<=', action.payload.max).
.where('location', '>=', action.payload.min)
.map(response => fetchNearbyStoresFulfilled(response))
.takeUntil(action$.ofType(FETCH_NEARBY_STORES))
);
这应该会在另一次移动时立即取消订阅请求。 (在我的脑海中,我不记得
action$
在 redux-observable
中的行为。您可能需要将 skip(1)
附加到传递给 takeUntil
的 observable 中。试试看。)而且,正如 Mark 所提到的,这是基于在取消订阅时取消请求的底层实现。
关于rxjs - 取消之前的请求,只使用 redux observable 触发最新的请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50160430/