Skip to main content

FromFuture

FromFuture#

FromFuture is a typeclass to convert scala.concurrent.Future to an effect, F[_]. So if there are some APIs returning Future, it can be converted to F[_].

There are three FromFuture instances available.

  • FromFuture for cats.effect.IO
  • FromFuture for scala.concurrent.Future
  • FromFuture for cats.Id
trait FromFuture[F[_]] {  def toEffect[A](future: => Future[A]): F[A]}

FromFuture.toEffect#

import cats._import cats.syntax.all._import cats.effect._
import effectie.cats._import effectie.cats.Effectful._
import effectie.concurrent.ExecutorServiceOps
import java.util.concurrent.{ExecutorService, Executors}import scala.concurrent.{ExecutionContext, Future}import scala.concurrent.duration._
object MyApp {
  def foo(n: Int)(implicit ec: ExecutionContext): Future[Int] =    Future(n + 100)
  def bar[F[_]: Fx](n: Int): F[Int] =    pureOf(n * 2)
  def baz[F[_]: Monad: Fx: FromFuture](n: Int)(implicit ec: ExecutionContext): F[Int] =    for {      a <- FromFuture[F].toEffect(foo(n))      b <- bar[F](a)    } yield b
}
val executorService: ExecutorService =  Executors.newWorkStealingPool(Runtime.getRuntime.availableProcessors() >> 1)// executorService: ExecutorService = java.util.concurrent.ForkJoinPool@6dbf8b97[Terminated, parallelism = 1, size = 0, active = 0, running = 0, steals = 1, tasks = 0, submissions = 0]implicit val ec: ExecutionContext = ExecutionContext.fromExecutorService(executorService)// ec: ExecutionContext = scala.concurrent.impl.ExecutionContextImpl$$anon$4@7382c4e9implicit val cs: ContextShift[IO] = IO.contextShift(ec)// cs: ContextShift[IO] = cats.effect.internals.IOContextShift@2f83503
try {   println(MyApp.baz[IO](1).unsafeRunSync())} finally {  ExecutorServiceOps.shutdownAndAwaitTermination(executorService, 1.second)}// 202