How to do recurrent events in react/react-native with redux?

558 views Asked by At

I am doing a react native application that on certain action of the user will start tracking gps position, and on other stop.

But i am hitting some road block not finding the correct way of doing this time based position tracker as it does not seem natural for the pattern. Here are the ideas I had:

  1. Treat it as async using redux-thunk.
  2. Use redux-observable timed event.
  3. Use sagas.
  4. Use SetTimeout in my component (is the simplest solution but I don't want to stop my users from navigating around, and i dont thing this is a UI responsability)
1

There are 1 answers

0
Kanekotic On BEST ANSWER

So I am going to leave this as reference for the future, with the simple solution i got finally working while i was working on writing this question.

import * as types from './types'
var gpsGetInterval 
export function startLocationTracking(time = 1000){
    return dispatch => {
            gpsGetInterval = setInterval(() =>{
                navigator.geolocation.getCurrentPosition(
                (position) => {
                    dispatch({
                        type: types.NEW_POSITION,
                        state: JSON.stringify(position)
                    })
                })
            }, time) 
            dispatch({
                type: types.START_RUN
            })
        }
}

export function stopLocationTracking(){
    clearInterval(gpsGetInterval)
    return {
        type: types.STOP_RUN
    }
}

So i understand that this might not be scalable and you might need to use epics under redux-observable or sagas. The difficulty that I faced in this 2 where:

  • using redux-observable clear the recurring event was not clear (or looked like a workaround to kind of pause it).
  • using sagas dont seem simple to scale or agregate.

With redux-observables here is the code i kind of got to, if anyone has a good idea for this kind of case i will like to hear about it :) :

export function inStartRun(action$){
  return action$.ofType(types.START_RUN)
    .switchMap(function () {
      Rx.Observable
        .interval(1000)
        .do(function () { console.log('tick...') })
        .share()
        .mapTo({ type: types.STOP_RUN})
    });
}

special thanks Jay Phelps in the question I made in the repo https://github.com/redux-observable/redux-observable/issues/168