Reputation: 34934
What I want to do is repeat GET requests to a server asynchronously over and over again so that I can synchronize the local data with the remote one. I'd like to do this by using Future
s without involving akka because I just want to understand the basic idea of how to do that at the lower level. No async
and await
preferably either because they are kind of the high level functions for Futures
and Promises
, thus I'd like to use Futures
and Promises
themselves.
So this is my functions:
def sendHttpRequestToServer(): String = { ... }
def send: Unit = {
val f = future { sendHttpRequestToServer() }
f onComplete {
case Success(x) =>
processResult(x) // do something with result "x"
send // delay if needed and send the request again
case onFailure(e) =>
logException(e)
send // send the request again
}
}
That's what I think it might be. How could I change it, is there any mistake in algorithm? Your thoughts.
UPDATE:
As I already know, futures are not designed for recurring tasks, only for one time ones. Therefore, they can't be used here. What do I use then?
Upvotes: 0
Views: 125
Reputation: 13667
Your code has some issues with exception handling. If an exception is thrown in processResult
or logException
the send
will no longer occur, breaking your loop. This exception will also not be logged. A better way is:
f.map(processResult).onFailure(logException)
f.onComplete(x => send())
This way the send
still happens despite exceptions in processResult
or logException
, exceptions from processResult
are logged, and the next send can begin intermediately while the results are still being processed. If you want to wait until processing is complete, you could do:
val f2 = f.map(processResult).recover { case e => logException(e) }
f2.onComplete(x => send())
Upvotes: 3