How to cling to action and epics?

I am familiar with React and Redux, but completely new to RxJS and observable decline.

I am working on a thread that I was able to solve with the following:

const reducer = (state, action)  => {
   switch(action.type) {
   // some other cases here
   case Types.LOCATION_GEOCODED: 
      const { address, place_id } = action
      return {...state, address, place_id }
   }
}

const updateLocationEpic = (action$, store) =>
   action$.ofType(Types.UPDATE_LOCATION)
   .mergeMap((action) =>
      Observable.fromPromise(reverseGeocode(store.getState().location))
      .map(({address, place_id}) => ({type: Types.LOCATION_GEOCODED, address, place_id}))
   )

const broadcastLocationEpic = (action$, store) =>
   action$.ofType(Types.LOCATION_GEOCODED)
   .map((action) => ({type: Types.NEW_CURRENT_LOCATION, store.getState().location}))

      

The first epic invokes the LOCATION_GEOCODED action after the asynchronous request, the reducer then "completes" the location information, and finally the second epic takes the full location from the state and broadcasts it.

The main point is that the NEW_CURRENT_LOCATION action is triggered after the reducer has processed the previous action (LOCATION_GEOCODED), because it needs to query the state that has just been updated.

The code above works, but I'm wondering if this could somehow be expressed in one epic, especially since I have another case where I need to wait for two activities that receive parallel requests, so I will need something- then do the same as what you would achieve with a Promise.all

template view

Is there a better way to accomplish this in one epic?

+3


source to share


1 answer


const updateLocationEpic = (action$, store) =>
    action$.ofType(Types.UPDATE_LOCATION)
        .mergeMap((action) => Observable.merge(
            Observable.fromPromise(reverseGeocode(store.getState().location))
                .map(({ address, place_id }) => ({ type: Types.LOCATION_GEOCODED, address, place_id })),

            action$.ofType(Types.LOCATION_GEOCODED)
                .map((action) => ({ type: Types.NEW_CURRENT_LOCATION, location: store.getState().location }))
        ));

      



0


source







All Articles