willriker's comments

willriker | 8 years ago | on: Understanding redux-saga: From action creators to sagas

Another benefit of redux-saga not mentioned here is the ability to build stateful sagas. For example, something like a game loop can be encoded in a saga like this:

export default function* playGame({ getState, selectors }) { yield take(GAME_READY);

  const refreshDelay = 1000 / FPS;

  while (true) { 
    yield take(START_GAME_PLAY);

    while (true) { 
      const {
        gameState: {
          speed,
          isPlaying,
          gameTime,
        },
      } = getState();

      if (!isPlaying) {
        // game play has stopped
        break;
      }

      const timeDelta = refreshDelay * speed;
      yield put(setGameTime(gameTime + timeDelta));

      // sleep
      yield call(delay, refreshDelay);
    }
  }
}
page 1