Skip to content

Instantly share code, notes, and snippets.

@dwijnand
Forked from shajra/Task.scala
Last active January 6, 2016 11:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dwijnand/715c62130938e66d566f to your computer and use it in GitHub Desktop.
Save dwijnand/715c62130938e66d566f to your computer and use it in GitHub Desktop.
Integration code between Scalaz and Scala standard concurrency libraries.
import scalaz.\/
import scalaz.concurrent.Task
import scala.concurrent.{ ExecutionContext, Future, Promise }
import scala.util.Try
class TaskCompat(private val T: Task.type) extends AnyVal {
def fromScala[A](future: Future[A])(implicit ec: ExecutionContext): Task[A] =
Task async (handlerConversion andThen future.onComplete)
def fromScalaDeferred[A](future: => Future[A])(implicit ec: ExecutionContext): Task[A] =
Task delay fromScala(future)(ec) flatMap identity
def unsafeToScala[A](task: Task[A]): Future[A] = {
val p = Promise[A]
task runAsync (_ fold (p failure _, p success _))
p.future
}
private def handlerConversion[A]: ((Throwable \/ A) => Unit) => Try[A] => Unit =
callback => (t: Try[A] => \/ fromTryCatch t.get) andThen callback
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment