scalamonadsfuturescala-catstagless-final

Transform Future[A] to F[A] with Async[F]


I'm working with Slick and Cats.

database.run returns a Future, but I need the method of my class (generic on F[_]: Async) to return a monad F. I can make it work like this

val future = database.run(insertion)    
val result = Await.result(future, Duration.Inf)    
Async[F].delay(result)

but that is not the way it should be done for sure, since it's blocking the thread.

Is there any proper way to do this?


Solution

  • Async.fromFuture is what you need.
    As always, the scaladoc is yout friend.

    import cats.effect.{Async, ContextShift]
    
    def foo[F[_] : Async : ContextShift]: F[Result] =
      Async.fromFuture(Async[F].delay(database.run(insertion)))