Incerteza
Incerteza

Reputation: 34934

An alternative to "while" for making repeated requests to a server

I have a function which should return a result either from the db or a server. But the server might fail and return nothing and in that case I need to repeat the server request until it returns the result:

def getToken() = 
  getTokenFromDb orElse getTokenFromServer() map { t =>
    saveTokenToDb(t)
    t
  }

What is a sensible solution for repetitive requests to getTokenFromServer() until I get a good response from it except using while loop? Of maybe using while is a good solution?

Upvotes: 0

Views: 388

Answers (2)

Felix
Felix

Reputation: 8505

This may sound insane, but you could create a stream of infinite server-requests, and then use "takeWhile + isDefined" :) I think that may actually be quite easy to implement. If I get to my code-machine, I'll whip something up :)

Upvotes: 2

Alexander Arendar
Alexander Arendar

Reputation: 3435

Well, as far as you have no specific requirements on how many attempts you want it to try the server, just use recursion. This is in fact almost the same as while loop :) but in more functional style. So make the getTokenFromServer() recursive. But do not forget about the tail-recursion, i.e. the recursive call to the getTokenFromServer() from within itself must be a last code statement in it's code. That way you will not get any troubles with stack overflowing.

Upvotes: 0

Related Questions