2017-09-29 3 views
1

Ich habe gerade angefangen Redux-Observable zu verwenden. Ich möchte ein generisches Epic erstellen, das Daten vom Server anfordert. Ich möchte, dass mehrere Anfragen mit derselben Aktion und ID entlarvt werden. Ich bin mir jedoch nicht sicher, wie ich das machen könnte, ohne mehrere Epen zu erstellen.Generic Epic mit Redux-Observable

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')))); 

Wie ist es möglich, ein generisches Epic zu erstellen, das basierend auf Aktion und ID debugnet?


Update: wusste nie über GroupBy. Es funktionierte gut mit switchMap. Das Folgende ist, wurde ich benutzt.

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'))) 
      ); 
    ) 

Antwort

3

Sie können das groupBy Betreiber:

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'))) 
      ); 
    ) 

Die actionByIdGroup $ ist eine gruppierte beobachtbare der gleichen Aktion ids. Das bedeutet, dass nur Aktionen mit derselben ID Teil desselben Streams sind. In diesem Fall wird die debounceTime für Aktionen mit derselben ID angewendet.