Last active
February 4, 2019 14:10
-
-
Save fthomas/37aed4686ec98450bc9fc97b9f2fb1ef 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
object AsyncCallbackInstances { | |
implicit val asyncCallbackAsync: Async[AsyncCallback] = new Async[AsyncCallback] { | |
override def async[A](k: (Either[Throwable, A] => Unit) => Unit): AsyncCallback[A] = | |
AsyncCallback((cb: Try[A] => Callback) => Callback(k(r => cb(r.toTry).runNow()))) | |
override def asyncF[A](k: (Either[Throwable, A] => Unit) => AsyncCallback[Unit]): AsyncCallback[A] = | |
AsyncCallback((cb: Try[A] => Callback) => k(r => cb(r.toTry).runNow()).toCallback) | |
override def suspend[A](thunk: => AsyncCallback[A]): AsyncCallback[A] = | |
AsyncCallback.byName(thunk) | |
override def bracketCase[A, B](acquire: AsyncCallback[A])(use: A => AsyncCallback[B])( | |
release: (A, ExitCase[Throwable]) => AsyncCallback[Unit]): AsyncCallback[B] = | |
acquire.flatMap { a => | |
use(a).attempt.flatMap { | |
case Right(b) => release(a, ExitCase.Completed).map(_ => b) | |
case Left(t) => release(a, ExitCase.Error(t)).flatMap(_ => AsyncCallback.throwException(t)) | |
} | |
} | |
override def raiseError[A](e: Throwable): AsyncCallback[A] = | |
AsyncCallback.throwException(e) | |
override def handleErrorWith[A](fa: AsyncCallback[A])(f: Throwable => AsyncCallback[A]): AsyncCallback[A] = | |
fa.attempt.flatMap { | |
case Right(a) => AsyncCallback.pure(a) | |
case Left(t) => f(t) | |
} | |
override def pure[A](a: A): AsyncCallback[A] = | |
AsyncCallback.pure(a) | |
override def flatMap[A, B](fa: AsyncCallback[A])(f: A => AsyncCallback[B]): AsyncCallback[B] = | |
fa.flatMap(f) | |
override def tailRecM[A, B](a: A)(f: A => AsyncCallback[Either[A, B]]): AsyncCallback[B] = | |
AsyncCallback.tailrec(a)(f) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment