Last active
March 18, 2018 16:57
-
-
Save JohnMurray/786bf9820c5b80a06f7e339e1d0a9d4d to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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