Blog>
Snippets

Handling Side Effects in Isolated Clones

Explores creating and managing isolated clones of a generator to handle side effects in a controlled manner, ensuring that side effects from one clone do not interfere with another.
function* mainSaga(data) {
  // Complex logic with side effects here
  yield 'Some side effect result';
}
Defines the main saga generator function which includes logic that yields side effects.
function cloneableGenerator(generatorFunction) {
  const history = [];
  const cloneGen = function* (...args) {
    const it = generatorFunction(...args);
    let result;
    let index = 0;
    while (true) {
      if (index < history.length) {
        result = it.next(history[index]);
      } else {
        result = it.next(result && result.value);
        history.push(result);
      }
      if (result.done) break;
      yield result.value;
      index++;
    }
  };
  return cloneGen;
}
Creates a higher-order function to create isolated clones of a generator. It records each yielded value to ensure clones can replicate the generator's state up to any point.
const clonedSaga = cloneableGenerator(mainSaga);

// Creating multiple isolated clone instances
cnst clone1 = clonedSaga();
const clone2 = clonedSaga();
Instantiates the cloneable generator function and creates two isolated clones from the main saga generator.
console.log(clone1.next().value); // Proceed with clone1 without affecting clone2
console.log(clone2.next().value); // Independently proceed with clone2
Demonstrates using the isolated clones to proceed through the saga's logic independently, ensuring that side effects in one do not affect the other.