StopKran StopKran - 10 months ago 83
Scala Question

How to use Future inside DBIOAction composition in slick 3?

Slick 3 offers DBIOAction composition by using flatMap method. Also, we can do some calculations in back-end between two DBIOActions. That's works fine in most cases, but what I should do when calculations result is in the monad like Future? There is code with blocking way:

val fooQuery = TableQuery[FooTable]
val barQuery = TableQuery[BarTable]

def requestService(content: Iterable[String]): Future[Iterable[Long]] = ???

def modify(ids: Iterable[Long], change: String) = {

val query = fooQuery.filter( inSet ids).result.flatMap{ fooSeq =>
val content =
val requestServiceFuture = requestService(content)

val serviceResult = Await.result(requestServiceFuture, 1.minute)
barQuery.filter( inSet serviceResult).delete //or other action

Is there way to perform this code asynchronously, without Await?

Answer Source

You can create DBIO from Future using DBIOAction.from and then compose with other DBIOs using flatMap

val query = for {
    fooSeq <- fooQuery.filter( inSet ids).result
    content =
    serviceResult <- DBIOAction.from(requestService(content))
    result <- barQuery.filter( inSet serviceResult).delete
} yield result$