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 monix.eval.Task
  • 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 monix.eval._
import effectie.monix._
import effectie.monix.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@4500eb5[Terminated, parallelism = 1, size = 0, active = 0, running = 0, steals = 0, tasks = 0, submissions = 0]
implicit val ec: ExecutionContext = ExecutionContext.fromExecutorService(executorService)
// ec: ExecutionContext = scala.concurrent.impl.ExecutionContextImpl$$anon$4@283faad
import monix.execution.Scheduler.Implicits.global
try {
println(MyApp.baz[Task](1).runSyncUnsafe())
} finally {
ExecutorServiceOps.shutdownAndAwaitTermination(executorService, 1.second)
}
// 202