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)
}
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)
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With