Skip to content

Instantly share code, notes, and snippets.

@danslapman
Created May 16, 2018 10:16
Show Gist options
  • Save danslapman/960f49fb36e43fed1a0115cfcc2d02b6 to your computer and use it in GitHub Desktop.
Save danslapman/960f49fb36e43fed1a0115cfcc2d02b6 to your computer and use it in GitHub Desktop.
Parallel lazy future with cats
interp.configureCompiler(_.settings.YpartialUnification.value = true)
import $file.`conf`
import $ivy.`org.typelevel::cats-core:1.1.0`
import cats._
import cats.data.ReaderT
import cats.instances.future._
import cats.syntax.parallel._
import scala.concurrent.ExecutionContext.global
import scala.concurrent.duration._
import scala.concurrent.{Await, ExecutionContext, Future}
import scala.language.higherKinds
import scala.language.postfixOps
trait Repo[F[_]] {
def getFoo(x: Int): F[String]
}
trait Service[F[_]] {
def someMethod(s: String): F[Int]
}
type PimpedFuture[A] = ReaderT[Future, ExecutionContext, A]
object PimpedFuture {
def apply[T](value: => T): PimpedFuture[T] = ReaderT.apply { implicit ExecutionContext =>
Future(value)
}
}
object RPF extends Repo[PimpedFuture] {
def getFoo(x: Int): PimpedFuture[String] = {
PimpedFuture {
println(s"running getFoo with $x")
Thread.sleep(5000)
x.toString
}
}
}
object SPF extends Service[PimpedFuture] {
def someMethod(s: String): PimpedFuture[Int] = {
PimpedFuture {
println(s"running getBar with $s")
Thread.sleep(10)
s.length
}
}
}
implicit val parf = Parallel.identity[Future](catsStdInstancesForFuture(global))
val pf = (RPF.getFoo(1), SPF.someMethod("foo")).parMapN((_, _) => ()).run(global)
Await.ready(pf, 10 seconds)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment