title: How to poll with a Future in Scala?
body: <p>I want to poll an API endpoint until it reaches some condition. I expect it to reach this condition in couple of seconds to a minute. I have a method to call the endpoint that returns a <code>Future</code>. Is there some way I can chain <code>Future</code>s together to poll this endpoint every <code>n</code> milliseconds and give up after <code>t</code> tries?</p>
  
  <p>Assume I have a function with the following signature:</p>
  
  <pre><code>def isComplete(): Future[Boolean] = ???
  </code></pre>
  
  <p>The simplest way to do this in my opinion would be to make everything blocking:</p>
  
  <pre><code>def untilComplete(): Unit = {
    for { _ &lt;- 0 to 10 } {
      val status = Await.result(isComplete(), 1.seconds)
      if (status) return Unit
      Thread.sleep(100)
    }
    throw new Error("Max attempts")
  }
  </code></pre>
  
  <p>But this may occupy all the threads and it is not asynchronous. I also considered doing it recursively:</p>
  
  <pre><code>def untilComplete(
      f: Future[Boolean] = Future.successful(false),
      attempts: Int = 10
    ): Future[Unit] = f flatMap { status =&gt;
      if (status) Future.successful(Unit)
      else if (attempts == 0) throw new Error("Max attempts")
      else {
        Thread.sleep(100)
        untilComplete(isComplete(), attempts - 1)
      }
  }
  </code></pre>
  
  <p>However, I am concerned about maxing out the call stack since this is not tail recursive.</p>
  
  <p>Is there a better way of doing this?</p>
  
  <p>Edit: I am using akka</p>