Home > database >  Calling slow future returning function in scala for each item in a Seq
Calling slow future returning function in scala for each item in a Seq

Time:10-08

I have this sample code currently but the issue is that slowFunction() below isn't running at all.

Is it possible to trigger the next function call after the function call on the previous item returns? It doesn't really matter as long as the function gets executed at least once for each item but thought it would help with the load on the system.

import scala.concurrent.Future
import scala.concurrent.ExecutionContext.Implicits.global
import scala.util.{Failure, Success}

val inputsFromDb = Future { Seq(1, 2, 3) }

def slowFunction(input: Int): Future[Boolean] = {
  Future {
    Thread.sleep(1000)
    println(s"Returning from slow function for input $input")
    true    
  }
}

val results: Future[Boolean] = inputsFromDb.flatMap { inputs =>
  val updateResults = inputs.map { input =>
    println(s"Calling slow function for input $input")
    slowFunction(input)
  }
  Future.sequence(updateResults).map(_ => true)
}

results // Future(<not completed>)

Here's the output if I run the code as is.

Calling slow function for input 1
Calling slow function for input 2
Calling slow function for input 3

However it runs fine when I comment out the sleep part Thread.sleep(1000)

Calling slow function for input 1
Calling slow function for input 2
Calling slow function for input 3
Returning from slow function for input 3
Returning from slow function for input 2
Returning from slow function for input 1

If I can't get this working, I might just add a delay between each call to slowFuction by using java.util.Timer

CodePudding user response:

It looks like your program (or worksheet) is terminating before all the Futures reach completion.

Your code produces the expected output if, at some point before the program exits, you Await until results completes.

import scala.concurrent.duration._
scala.concurrent.Await.result(results, 999.millis)

As demonstrated in this Scastie session.

  • Related