Last active
January 31, 2017 09:20
-
-
Save atamborrino/d3660ae7910ae8ec8dd67ec023386478 to your computer and use it in GitHub Desktop.
UnfailableFuture is a subset type of Future that can not result in a failure.
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
import scala.concurrent.{ExecutionContext, Future} | |
import scala.util.control.NonFatal | |
// private constructor guarantees that we can not build a semantically incorrect UnfailableFuture | |
class UnfailableFuture[A] private (val value: Future[A]) extends AnyVal | |
object UnfailableFuture { | |
def apply[A](fut: Future[A], fallback: Throwable => A)(implicit ec: ExecutionContext): UnfailableFuture[A] = { | |
val futWithFallback = fut.recover { | |
case NonFatal(failure) => fallback(failure) | |
} | |
new UnfailableFuture(futWithFallback) | |
} | |
def successful[A](a: A) = new UnfailableFuture(Future.successful(a)) | |
} | |
// Example: allow to safely wrap a processing function to pass it in failure-sensitive context (like .pipeTo in an actor) | |
// with type-checking. | |
def handleFailure(userProcessingFunction: Input => Future[Output]): Input => UnfailableFuture[Output] = { | |
... | |
} | |
class MyActor(userProcessingFunction: Input => UnfailableFuture[Output]) extends Actor { | |
... | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment