Last active
August 29, 2015 14:00
-
-
Save mathieuancelin/11062752 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
import scala.util.control.NoStackTrace | |
package object FlatFuture { | |
case object EmptyOption extends RuntimeException("Current option is empty :'(") with NoStackTrace | |
implicit final class futureOfOptionToFuture[A](future: Future[Option[A]]) { | |
def flatten(implicit ec: ExecutionContext): Future[A] = { | |
future.flatMap { | |
case Some(something) => Future.successful(something) | |
case None => Future.failed(EmptyOption) | |
} | |
} | |
def flattenM(none: => Future[A])(implicit ec: ExecutionContext): Future[A] = { | |
future.flatMap { | |
case Some(something) => Future.successful(something) | |
case None => none | |
} | |
} | |
def flatten(none: => A)(implicit ec: ExecutionContext): Future[A] = { | |
future.flatMap { | |
case Some(something) => Future.successful(something) | |
case None => Future.successful(none) | |
} | |
} | |
def flattenM[O](some: A => Future[O], none: => Future[O])(implicit ec: ExecutionContext): Future[O] = { | |
future.flatMap { | |
case Some(something) => some(something) | |
case None => none | |
} | |
} | |
def flatten[O](some: A => O, none: => O)(implicit ec: ExecutionContext): Future[O] = { | |
future.flatMap { | |
case Some(something) => Future.successful(some(something)) | |
case None => Future.successful(none) | |
} | |
} | |
} | |
} |
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
import foo.bar.FlatFuture._ | |
val fuuu1: Future[Option[String]] = Future.successful(Some("Hello")) | |
val fuuu2: Future[Option[String]] = Future.successful(None) | |
implicit val ec = ExecutionContext.Implicits.global | |
fuuu1.flatten.filter(_ == "Hello").onComplete { | |
case Success(str) if str == "Hello" => println("It works") | |
case _ => println("Error ...") | |
} | |
fuuu2.flatten.onComplete { | |
case Failure(e) => println("It works") | |
case _ => println("Error ...") | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment