Blog>
Snippets

Dynamic race conditions based on application state

Explores creating dynamic race conditions using Redux-Saga, where the tasks being raced change based on the application state, demonstrating how to structure sagas for adaptable concurrency.
import { select, call, race } from 'redux-saga/effects';

function* dynamicRaceSaga() {
  // Retrieve the current app state to decide which tasks to race
  const appState = yield select(state => state);
  const tasksToRace = {};

  // Based on the application state, dynamically create the task objects for racing
  if (appState.featureA.isActive) {
    tasksToRace.taskA = call(handleTaskA);
  }
  if (appState.featureB.isActive) {
    tasksToRace.taskB = call(handleTaskB);
  }
  // You can add more conditions based on your application needs

  // Racing the dynamically chosen tasks
  const winner = yield race(tasksToRace);

  console.log('Race winner:', winner);
}

function* handleTaskA() { /* task A implementation */ }
function* handleTaskB() { /* task B implementation */ }
This code snippet demonstrates how to dynamically set up race conditions in Redux-Saga based on the application state. It first selects the current state of the application to decide which tasks (in this case, handleTaskA and handleTaskB) to include in a race condition. Then, it creates an object `tasksToRace` dynamically populated with tasks based on the application state conditions. Finally, it uses the `race` effect from Redux-Saga to run these tasks concurrently, 'racing' them against each other to see which one finishes first. This approach allows for flexible and adaptable race conditions that can change based on the state of the application.