Created
October 28, 2015 23:34
-
-
Save japgolly/e511e05023474674c9a8 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 japgolly.scalajs.react | |
import scala.concurrent.duration.Duration | |
import scala.concurrent.{ExecutionContext, Await, Future} | |
object Blah { | |
private val DefaultMaxWait = Duration.Inf | |
implicit class FutureExt[A](val f: Future[A]) { | |
def toBlockingCallback: CallbackTo[A] = | |
toBlockingCallback(DefaultMaxWait) | |
def toBlockingCallback(maxWait: Duration): CallbackTo[A] = | |
CallbackTo(Await.result(f, maxWait)) | |
} | |
implicit class FutureCallbackToExt[A](val f: Future[CallbackTo[A]]) { | |
// def toBlockingCallbackFlat: CallbackTo[A] = | |
// toBlockingCallbackFlat(MaxWait) | |
// | |
// def toBlockingCallbackFlat(maxWait: Duration): CallbackTo[A] = | |
// f.toBlockingCallback(maxWait).flatten | |
def toCBF(implicit ec: ExecutionContext): CallbackTo[Future[A]] = | |
CallbackTo pure f.flattenCB | |
def flattenCB(implicit ec: ExecutionContext): Future[A] = | |
f.map(_.runNow()) | |
} | |
implicit class FutureCallbackExt(val f: Future[Callback]) { | |
def toCallback(implicit ec: ExecutionContext): Callback = | |
f.toCBF.void | |
} | |
// ------------------------------------------------------------------------------------------------------------------- | |
implicit class CallbackExt[A](val c: CallbackTo[A]) { | |
def await[B](implicit ev: A =:= Future[B]): CallbackTo[B] = | |
await(DefaultMaxWait) | |
def await[B](maxWait: Duration)(implicit ev: A =:= Future[B]): CallbackTo[B] = | |
c.flatMap(ev(_).toBlockingCallback(maxWait)) | |
// WARNING: Triggers execution | |
def toFuture: Future[A] = | |
c.async.runNow() | |
// WARNING: Triggers execution | |
def toFlatFuture[B](implicit ev: A =:= Future[B], ec: ExecutionContext): Future[B] = | |
toFuture.flatMap(ev) | |
} | |
// ------------------------------------------------------------------------------------------------------------------- | |
object Test1 { | |
def test(c: Callback) = () | |
val ajax: Future[Callback] = ??? | |
test(ajax.toCallback) // Doesn't block. Good. | |
} | |
object Test2 { | |
def test(c: Callback) = () | |
val ajaxCB: CallbackTo[Future[Callback]] = ??? | |
test(ajaxCB.flatMap(_.toCallback)) // Doesn't block. Good. | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment