Skip to content

Instantly share code, notes, and snippets.

@JohnMurray
Last active June 21, 2018 20:33
Show Gist options
  • Save JohnMurray/40b1768fd38c430784b10a0d91b1968a to your computer and use it in GitHub Desktop.
Save JohnMurray/40b1768fd38c430784b10a0d91b1968a to your computer and use it in GitHub Desktop.
import scala.concurrent.ExecutionContext.Implicits.global
class ApiService[T](limit: Long, timeFrame: FiniteDuration) {
// previous code ...
private def makeRequest(): Unit = requestQueue.pollFirst() match {
case null => // do nothing
case req =>
requestCount += 1
val res = req.f()
res.onComplete {
// re-queue at the head of the queue on failure and
// attempt to make another request
case Failure(_: Throwable) => this.synchronized {
requestQueue.offerFirst(req)
tryRequest()
}
// complete the promise for the future we gave back to the
// user and attempt to make anothe request on success
case Success(result) =>
req.p.complete(Success(result))
}
tryRequest()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment