Skip to content

Instantly share code, notes, and snippets.

@JohnMurray
Last active March 18, 2018 16:57
Show Gist options
  • Save JohnMurray/786bf9820c5b80a06f7e339e1d0a9d4d to your computer and use it in GitHub Desktop.
Save JohnMurray/786bf9820c5b80a06f7e339e1d0a9d4d to your computer and use it in GitHub Desktop.
class ApiService[T](limit: Long, timeFrame: FiniteDuration) {
// other code ...
private def makeRequest(): Unit = {
val req = requestQueue.pollFirst()
if (req == null) {
return
}
requestCount += 1
val result = req.f()
// re-queue at the head of the queue on failure and
// attempt to make another request
def retry(): Unit = this.synchronized {
requestQueue.offerFirst(req)
tryRequest()
}
result.onComplete {
case Failure(t: Throwable) =>
if (req.limitDetector(Left(t))) {
retry()
} else {
req.p.complete(Failure(t))
}
case Success(r) =>
if (req.limitDetector(Right(r))) {
retry()
} else {
req.p.complete(Success(r))
tryRequest()
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment