rxjs - 取消之前的请求,只使用 redux observable 触发最新的请求

标签 rxjs redux-observable

所以我有一个用例,我在移动 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 has flatMap 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 is mergeMap 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 之前,该请求不会被取消。 .如果您想在另一次移动时立即取消任何未决请求 - 而不是等待去抖动持续时间 - 您可以使用 takeUntilFETCH_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/

相关文章:

javascript - Redux Observable 节流 Ajax 请求仅满足某些条件

Redux Observable : How to use action. 有效载荷在链的后半部分?

typescript - 如何从angular2中的observable中获取数据

javascript - Angular2 RxJS - 分割 url 集合以获取更小的 block

javascript - 使用 RxJS switchMap 仅取消订阅具有相同请求 URL/操作负载的流(redux-observable 史诗)

redux-可观察的离线/乐观行为

javascript - switchMap 由 RxJs 中的属性区分

Angular Observable 错误处理

状态为 : 200 for URL: null 的 Angular 2 + NativeScript 响应

Angular Jasmine 测试无法触发使用 fromEvent rxjs 运算符创建的 Observable