title: managing state with FRP
body: <p>Some say that FRP is about handling event streams without explicitly managing state. This person, for example:</p>
  
  <p><a href="http://www.slideshare.net/borgesleonardo/functional-reactive-programming-in-clojurescript" rel="nofollow">http://www.slideshare.net/borgesleonardo/functional-reactive-programming-in-clojurescript</a></p>
  
  <p>Others motivate FRP by pointing out the difficulties of programming entirely by side-effects, as one must do with asynchronous callbacks.</p>
  
  <p><a href="http://cs.brown.edu/~sk/Publications/Papers/Published/mgbcgbk-flapjax/" rel="nofollow">http://cs.brown.edu/~sk/Publications/Papers/Published/mgbcgbk-flapjax/</a></p>
  
  <p>However in experimenting with FRP (flapjax), I keep hitting the same problem: an inability to handle state, except explicitly, via side-effects.</p>
  
  <p>For example, an animation queue. Changes arrive on an event stream. When the first change arrives, I need to queue a draw to happen some time in the future (e.g. with window.requestAnimationFrame), and arrange to accumulate changes between now and the future draw event. When the draw event happens, I need to draw the accumulated changes.</p>
  
  <p>This is about six lines of code using an imperative style with observer pattern, but I can't find a reasonable way to express this in FRP. The only thing that comes close involves closing the related event streams over a shared state, and explicitly managing the state and rendering events via side-effects. It's hardly an improvement on imperative callbacks.</p>
  
  <p>How is this supposed to be handled in FRP?</p>
  
  <p>Here's a flapjax utility for closing over state:</p>
  
  <pre><code>function worldE(init, handlers) {
      var r = fj.receiverE();
      fj.forEach(function(h) {
          h[0].mapE(function (ev) {
              r.sendEvent(init = h[1](init, ev));
          });
      }, handlers);
      return r;
  }
  </code></pre>
  
  <p>And here it is used in an animation loop:</p>
  
  <pre><code>function initialize(opts) {
      var blitE = fj.receiverE();
  
      function accumulate(state, data) {
          if (!state.queued) {
              window.requestAnimationFrame(blitE.sendEvent);
          }
          return {queued: true, changes: _.extend({}, state.changes, data)};
      }
  
      function dodraw(state, _) {
          draw(state.changes);
          return {queued: false, changes: {}};
      }
  
      worldE({queued: false, changes: {}},
              [[opts.data_source, accumulate], [blitE, dodraw]]);
  }
  </code></pre>
  
  <p>Things to note: it's larger, less readable and less maintainable than the equivalent callback code. It still requires explicitly managing state. And it operates via side effects.</p>
  
  <p>Is there a better way of doing this in FRP? A different pattern, or a different library?</p>