简体   繁体   English

使用Redux-Observable的通用史诗

[英]Generic Epic using Redux-Observable

I just started using Redux-Observable. 我刚开始使用Redux-Observable。 I want to make a generic epic that requests data from the server. 我想制作一个从服务器请求数据的通用史诗。 I want multiple requests with same action and id to be debounced. 我想要多个具有相同动作和id的请求被去抖动。 However, I'm not sure how to do this without creating multiple epics. 但是,我不知道如何在不创建多个史诗的情况下如何做到这一点。

const TYPE_IFEXISTS_REQUEST = 'IFEXISTS_REQUEST';
export const IFEXISTS_REQUEST = (id, value) =>
  ({ type: TYPE_IFEXISTS_REQUEST, id, value });
export const IFEXISTS_EPIC = action$ =>
  action$
    .ofType(TYPE_IFEXISTS_REQUEST)
    .debounceTime(5000) // ERROR: debounces based on action type and not id
    .mergeMap(action =>
      fromPromise(api.get(`/api/exists/${action.id}/${action.value}`))
        .map(({ data }) => IFEXISTS_SUCCESS(action.id, data))
        .catch(() => of(IFEXISTS_FAILURE(action.id, 'Server error'))));

How is it possible to create a generic epic that debounces based on both action and id? 怎样才能创建一个基于动作和id去抖动的通用史诗?


Update: Never knew about GroupBy. 更新:从不了解GroupBy。 It worked well with switchMap. 它适用于switchMap。 The following is was I used. 以下是我用过的。

action$
    .ofType(TYPE_IFEXISTS_REQUEST)
    .groupBy(action => action.id)
    .mergeMap(actionByIdGroup$ => 
        actionByIdGroup$
            .debounceTime(5000) // debounces based on action id
            .switchMap(action =>
                fromPromise(api.get(`/api/exists/${action.id}/${action.value}`))
                    .map(({ data }) => IFEXISTS_SUCCESS(action.id, data))
                    .catch(() => of(IFEXISTS_FAILURE(action.id, 'Server error')))
            );
    )

You can use the groupBy operator: 您可以使用groupBy运算符:

  action$
    .ofType(TYPE_IFEXISTS_REQUEST)
    .groupBy(action => action.id)
    .mergeMap(actionByIdGroup$ => 
        actionByIdGroup$
            .debounceTime(5000) // debounces based on action id
            .mergeMap(action =>
                fromPromise(api.get(`/api/exists/${action.id}/${action.value}`))
                    .map(({ data }) => IFEXISTS_SUCCESS(action.id, data))
                    .catch(() => of(IFEXISTS_FAILURE(action.id, 'Server error')))
            );
    )

The actionByIdGroup$ is a Grouped Observable of the same action ids. actionByIdGroup $是一个具有相同动作ID的Grouped Observable。 Meaning, only actions with the same id will be part of the same stream. 意思是,只有具有相同id的动作才会成为同一个流的一部分。 In this case, the debounceTime will be applied for actions with the same id. 在这种情况下, debounceTime将应用于具有相同ID的操作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM