Last active
September 26, 2018 19:24
-
-
Save marko-asplund/3910fed39250dc4905090feb5ba8919b to your computer and use it in GitHub Desktop.
This file contains 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
package object effect { | |
import cats.effect.IO | |
import scala.concurrent.Future | |
import language.implicitConversions | |
import language.higherKinds | |
import scala.util.{Success, Failure} | |
import scala.concurrent.Promise | |
import cats.effect.Effect | |
import cats.implicits._ | |
def translate[G[_], F[_], A]( | |
fa: => F[A] | |
)(implicit F: Effect[F], G: Effect[G]): G[A] = | |
G.delay(fa) >>= ( | |
ff => G.async(cb => F.runAsync(ff)(k => IO(cb(identity(k))))) | |
) | |
def fromTheFuture[F[_], A]( | |
ff: F[Future[A]] | |
)(implicit F: Effect[F]): F[A] = | |
ff >>= ( | |
f => | |
F.async { cb => | |
f.onComplete( | |
r => | |
cb(r match { | |
case Success(a) => Right(a) | |
case Failure(e) => Left(e) | |
}) | |
)(concurrent.ExecutionContext.Implicits.global) // continue on global ec | |
} | |
) | |
def backToTheFuture[F[_], A](fa: => F[A])(implicit F: Effect[F]): Future[A] = { | |
val p = Promise[A] | |
F.runAsync(fa)(cb => IO.async(k => cb.fold(p.failure, p.success))) | |
p.future | |
} | |
} | |
// usage | |
// F[A] from Future[A] | |
def hello(): Future[String] = ??? | |
val msg: F[String] = fromTheFuture(hello().pure[F]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment