LoranceChen
LoranceChen

Reputation: 2574

How to def Future onSuccess recursion to tailrec?

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

Answers (1)

Alexander Arendar
Alexander Arendar

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

Related Questions