Skip to content

Instantly share code, notes, and snippets.

@Tvaroh
Created September 25, 2018 16:18
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save Tvaroh/14cfe730357d31def9df2f4915d7c7de to your computer and use it in GitHub Desktop.
Save Tvaroh/14cfe730357d31def9df2f4915d7c7de to your computer and use it in GitHub Desktop.
import cats.effect.Async
import cats.implicits._
import scala.concurrent.{ExecutionContext, Future}
import scala.util.{Failure, Success}
/** Typeclass to wrap Scala futures. */
trait Execute[F[_]] {
implicit def async: Async[F]
def executionContext: F[ExecutionContext]
def deferFutureAction[T](f: ExecutionContext => Future[T]): F[T] =
executionContext.flatMap { implicit ec =>
async.async { callback =>
f(ec).onComplete {
case Success(r) => callback(Right(r))
case Failure(ex) => callback(Left(ex))
}
}
}
def deferFuture[T](future: => Future[T]): F[T] =
deferFutureAction(_ => future)
}
object Execute {
def apply[F[_]: Execute]: Execute[F] =
implicitly[Execute[F]]
implicit def asyncExecute[F[_]: Async](implicit ec: ExecutionContext): Execute[F] =
new Execute[F] {
override def async: Async[F] = Async[F]
override def executionContext: F[ExecutionContext] = ec.pure[F]
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment