Reputation: 2574
I don't know how to description exactly, see the code please
def callForever(f: Future[Int]): Unit = {
f.onComplete {
case Failure(e) =>
//do something
case Success(c) =>
// do again
val nextConn: Future[Int] = connection()
callForever(nextConn)
}
}
Its a normal recursion,actually,I use it to listen socket wait a Async connection.
Because it always running I want make it better, can I refactor it by a tailrec way?
Upvotes: 1
Views: 711
Reputation: 3425
I just thought that you may want to look at this way to do this which looks a bit better for me:
import scala.concurrent.Future
import scala.util.{Failure, Success, Random}
import scala.concurrent.ExecutionContext.Implicits.global
/**
* Created by Alex on 2/29/2016.
*/
object Test {
def giveMeValue:Future[Int] = Future.successful{Random.nextInt()}
def callForever(f:Future[Int]):Future[Int] = {
println("iteration")
f flatMap(i => {println(i); callForever(giveMeValue)})
}
def main(args: Array[String]) {
callForever(giveMeValue)
while(true){}
}
}
Upvotes: 1