12

Given the following example:

  val handler : Connection = new DatabaseConnectionHandler()
  val result : Future[Future[Future[Option[ResultSet]]]] = handler.connect
    .map( (parameters) => handler )
    .map( connection => connection.sendQuery("BEGIN TRANSACTION SERIALIZABLE") )
    .map( future => future.map( query => query.rows ) )
    .map( future => handler.sendQuery("COMMIT").map( query => future ) )

Is it possible to flatten it to receive a Future[Option[ResultSet]] at the end instead of this future inside a future inside a future structure in Scala?

I am currently using Scala's 2.10 Future's and Promise's, but I can't find a way to to this. I know I can use nested callbacks but I would rather avoid that since the code is going to look horrible.

The Connection trait is defined here.

Maurício Linhares
  • 39,901
  • 14
  • 121
  • 158

2 Answers2

25

Whenever you map with an argument of type A => Future[B] you should really be using flatMap.

The code would then be like this:

  val connection : Connection = new DatabaseConnectionHandler( DefaultConfiguration )
  val result: Future[QueryResult] = connection.connect
    .flatMap( _ => connection.sendQuery("BEGIN TRANSACTION ISOLATION LEVEL REPEATABLE READ") )
    .flatMap( _ => connection.sendQuery("SELECT 0") )
    .flatMap( _ => connection.sendQuery("COMMIT").map( value => query ) )

Alternatively, you could use for-comprehension. It uses flatMap for you.

val connection : Connection = new DatabaseConnectionHandler( DefaultConfiguration )
val result: Future[QueryResult] = for {
  _ <- connection.connect
  _ <- connection.sendQuery("BEGIN TRANSACTION ISOLATION LEVEL REPEATABLE READ")
  _ <- connection.sendQuery("SELECT 0")
  queryResult <- connection.sendQuery("COMMIT").map( value => query )
} yield { queryResult }
HEX
  • 1,647
  • 2
  • 15
  • 29
Debilski
  • 66,976
  • 12
  • 110
  • 133
  • 2
    There is no `flatten` in `scala.concurrent.Future` – senz May 13 '15 at 09:33
  • 2
    @senz Yes, `scala.concurrent.Future` don't have `flatten`. But you can use `f flatMap identity`. [See here](https://groups.google.com/forum/#!topic/scala-internals/yVYe_xnUOFA) – HEX Sep 07 '15 at 11:18
  • Are you mixing options and futures in your for-comprehension? Isn't that not allowed? – Brian Risk Jul 20 '18 at 13:59
8

You should use a flatMap instead of a map here.

The flatMap expects a function fun returning a future g and returns the future h holding the value from the future g that fun returned.

Also, consider writing this within a for-comprehension, see how here.

axel22
  • 32,045
  • 9
  • 125
  • 137