JohnBigs
JohnBigs

Reputation: 2811

How to return a value of Future when its done?

I wrote a simple method that returns List of Int based on a service call i perform in it.

my problem is that the service call im making is returning a future of some value, so I thought i can do onComplete and return what I want on complete of the future, but onComplete returns Unit...

this is how I wanted it to work:

  def getListOfInts(str: String): List[Int] = {
    myDaoService.findSomethingInDb(str).onComplete {
      case Success(res) =>
        res.map(line => line.amount.toInt*100).distinct.filter(num => num != 0).toList
      case Failure(exception) => logger.error(s"finding in db has failed with exeption: ", exception)
    }
  }

what is the right way to return the wanted value of a future when it completed?

i know usually its map/flatmap but this will keep it wrapped in the future and I want my method to return the actual value and not future of the value...

thanks!

Upvotes: 0

Views: 8458

Answers (2)

Nagarjuna Pamu
Nagarjuna Pamu

Reputation: 14825

Await.result is the way to go, but Its not recommended.

import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.duration._
import scala.concurrent.Await

def getListOfInts(str: String): List[Int] = {
  Await.result(myDaoService.findSomethingInDb(str), 10 seconds).map(line => line.amount.toInt*100).distinct.filter(num => num != 0).toList
}

The above way is not recommended until and unless you want to make the thread of execution wait(block) for the result. The above code does not scale.

Recommended way

def getListOfInts(str: String): Future[List[Int]] = 
myDaoService.findSomethingInDb(str).map { res =>
  res.map(line => line.amount.toInt*100).distinct.filter(num => num != 0).toList
}

The recommended way is to compose the future (use map and flatmap to transform the output type of the database call into the required result) and then finally doing waiting to get the final transformed result.

Upvotes: 2

sheunis
sheunis

Reputation: 1544

http://docs.scala-lang.org/overviews/core/futures.html

onComplete, onSuccess and onFailure are the callbacks you are looking for

Upvotes: 0

Related Questions