Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

replace a while loop with Future in scala

Tags:

scala

I have a function with return value of Future[Int]

def func: Future[Int] = {...}

I will periodically check the return value of func until it meet some condition(e.g. return value greater than 10), then I will take use of this return value to create other future value with map/flatmap.

How can I make this work without any synchronous code? which is listed below:

def check: Future[Int] = {
    var ret: Int = Await.result(func, Duration.Inf)
    while (ret <= 10) {
        ret = Await.result(func, Duration.Inf)
    }
    Future(ret + 100)
}
like image 371
user8341890 Avatar asked Jul 21 '17 04:07

user8341890


1 Answers

One way to achieve this is using recursion as shown below.

import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.Future

def check(func: () => Future[Int]): Future[Int] = {
    Future.unit.flatMap(_ => func()) flatMap {
        case x if x <= 10 => check(func)
        case x => Future.successful(x + 100)
    }
}
like image 179
rogue-one Avatar answered Sep 28 '22 18:09

rogue-one