FromFuture - Cats

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[_]: EffectConstructor](n: Int): F[Int] =
pureOf(n * 2)
def baz[F[_]: Monad: EffectConstructor: 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@51fb96d[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@64ab57da
implicit val cs: ContextShift[IO] = IO.contextShift(ec)
// cs: ContextShift[IO] = cats.effect.internals.IOContextShift@6cdb1c34
try {
println(MyApp.baz[IO](1).unsafeRunSync())
} finally {
ExecutorServiceOps.shutdownAndAwaitTermination(executorService, 1.second)
}
// 202