Created
September 25, 2018 16:18
-
-
Save Tvaroh/14cfe730357d31def9df2f4915d7c7de to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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