title: Immutable data in async systems
body: <p>I have a good idea of the benefits of using immutable data in my applications and I'm fairly comfortable with the idea of using these immutable structures in a simple synchronous programming environment.</p>
  
  <p>There's a good example somewhere on Stack Overflow that describes managing state for a game by passing the state along in a series of recursive calls, something like this:</p>
  
  <pre><code>function update(state) {
    sleep(100)
  
    return update({
      ticks: state.ticks + 1,
      player: player
    })
  }
  </code></pre>
  
  <p>We can do some arbitrary, side-effect free work in the body of the function, then we return a new state, rather than mutating the old one.</p>
  
  <p>It seems fairly easy to translate this to a simple async model, in say Javascript.</p>
  
  <pre><code>function update(state) {
    const newState = {
      player,
      ticks: state.ticks + 1
    };
  
    setTimeout(update.bind(this, newState), 100);
  }
  </code></pre>
  
  <p>However, as soon as we have more sources for asynchronous events, it seems to become a lot harder to manage to keep the state immutable and the functions pure.</p>
  
  <p>If we add a click event to the example, we end up with code that looks like this.</p>
  
  <pre><code>window.addEventListener('click', function() {
    // I have no idea what the state is
    // because only our update loop knows about it
  });
  </code></pre>
  
  <p>Now obviously, I don't want to mutate the state in this method, but I need to access state in order to create a new state, something like this.</p>
  
  <pre><code>window.addEventListener('click', function() {
    const state = getState();
  
    createState({
      player,
      clicks: clicks + 1
    });
  });
  </code></pre>
  
  <p>But it would seem like this requires some kind of mutable state manager?</p>
  
  <p>Alternatively, I suppose I could add the click event to a queue of actions to be processed within the update loop, something like:</p>
  
  <pre><code>window.addEventListener('click', function() {
    createAction('click', e);
  });
  
  function update(state, actions) {
    const newState = {
      player,
      ticks: state.ticks + 1,
      clicks: state.clicks + actions.clicks.length
    };
  
    setTimeout(update.bind(this, newState, []), 100);
  }
  </code></pre>
  
  <p>Again, this doesn't feel particularly functional and relies on at least some mutable state somewhere along the way. These are probably naive approaches coming from someone who has mostly worked with mutable state and imperative object oriented programming.</p>
  
  <p>What does the design for a system look like when there are multiple asynchronous event sources and we want everything to be immutable? Or at least, what's a good pattern for controlling mutability in a system like this?</p>