title: Dart/Flutter: How to best process hardware events in an infinite loop
body: <p>I have an infinite loop that runs in a an async function in a Flutter application (although the code is pure Dart, no Flutter API is used on it).</p>
  
  <p>Basically, it processes some math stuff, but I want to be able to update the data to be processed with an event coming from hardware (in this specific case from the microphone).</p>
  
  <p>In order to give the fast <code>while(true)</code> the opportunity to get events from the outside, I added a delay with a duration of zero.</p>
  
  <pre><code>doStuff() async {
    while (!stopFlag) {
      processMathStuff(dataModifiedByHardwareCallback);
  
      // Without this, the loop can't be interrupted.
      await Future.delayed(Duration.zero);
    }
  }
  </code></pre>
  
  <p>And although that seems to work in most platforms, calling <code>Future.delayed</code> like that makes this loop much slower than I would like. The question is if is it there a better (faster) way of doing this. This even looks kind of a hack to me. I tried calling <code>Future.delayed</code> only every a certain amount of iterations, but doing so even as often as every 10 iterations, the system loses events.</p>
  
  <p>By the way, <code>processMathStuff</code> does not contain loops internally, so it is really O(1).</p>
  
  <p><strong>NOTE:</strong> If I move the code to an Isolate, I get a similar problem with the Isolate not listening to the sendPort stuff if the <code>while(true)</code> lacks that kind of "yield".</p>