Skip to content

Instantly share code, notes, and snippets.

@shajra
Created August 23, 2013 03:34
Show Gist options
  • Save shajra/6315283 to your computer and use it in GitHub Desktop.
Save shajra/6315283 to your computer and use it in GitHub Desktop.
integration code between Scalaz and Scala standard concurrency libraries.
import concurrent.{ExecutionContext, Future => SFuture, Promise}
import util.Try
import _root_.scalaz.\/
import _root_.scalaz.concurrent.{Task => ZTask}
object Task {
def fromScala[A]
(future: SFuture[A])(implicit ec: ExecutionContext): ZTask[A] =
ZTask async (handlerConversion andThen future.onComplete)
def fromScalaDeferred[A]
(future: => SFuture[A])(implicit ec: ExecutionContext): ZTask[A] =
ZTask delay fromScala(future)(ec) flatMap identity
def unsafeToScala[A](task: ZTask[A]): SFuture[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