How convert Cats Effect 3 to Future

1.3k views Asked by At

I'm trying to combine Playframework with Cats Effect 3 Tagless Final style.

I'm stuck on the transformation to the Future. Play's Action requires either just value or Future, which I want to reach, for async processing.

def method = authed { _ => 
  val program: EitherT[IO, Throwable, Int] = ???
  program
}

def authed[F[_]: Async](fa: Request => F[Result]): Action = {
 ???
}

In cats effect 2 it was possible via _.toIO.unsafeToFuture but now it's changed. According to the doc I must use Dispatcher. Found the initial idea on Github but a new signature is F[Future[A]]

def beforeF[F[_]: Effect, A](fa: F[A]): Future[A] = fa.ioIO.unsafeToFuture()
// Note: Using a `Dispatcher` resource is cheap - don't worry about it
def preferredAfterF[F[_]: Async, A](fa: F[A]): F[Future[A]] = Dispatcher[F].use(_.unsafeToFuture(fa))

Does anyone have success?

1

There are 1 answers

0
Daenyth On

Contruct your routes so that they have access to a Disptacher object as a dependency, then the lifecycle will be appropriate

class MyRoute[F[_]: MonadThrow](disp: Dispatcher[F]) {
  def method = authed { _ => 
    val program: EitherT[IO, Throwable, Int] = ???
    disp.unsafeToFuture(program.value)
  }
}

(this might require some fiddling using allocated and the IORuntime's unsafeRunSync on a Dispatcher[IO] resource, depending on how your application is wired)