Created
March 18, 2015 16:41
-
-
Save petrovg/7e13a7d2e07564dfdacb to your computer and use it in GitHub Desktop.
Scala - Getting future result optionally and combining it with previous future result.
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
| // | |
| // Is there a better way to do this. The difficulty is coming from the fact that the | |
| // second future result may not be necessary, based on an optinal value in the first. | |
| // | |
| import scala.concurrent.{Await, Future} | |
| import scala.concurrent.duration._ | |
| import scala.concurrent.ExecutionContext.Implicits.global | |
| case class User(name: String, homepageUrl: Option[String]) | |
| case class UserProfile(userName: String, profile: String) | |
| def findUser = Future.successful(User("Bob", Some("http://bob.com"))) | |
| def downloadProfile(url: String): Future[String] = Future.successful("Profile from the interwebs...") | |
| def userProfile(userName: String): Future[UserProfile] = { | |
| // Is there a better way to do this??? | |
| findUser.flatMap { user => | |
| user.homepageUrl.map { url => | |
| downloadProfile(url).map { profile => | |
| UserProfile(user.name, profile) | |
| } | |
| }.getOrElse { | |
| // Specifically here, faking it with a future :( | |
| Future.successful(UserProfile(user.name, "<not set>")) | |
| } | |
| } | |
| } | |
| val profileFuture = userProfile("bob") | |
| Await.result(profileFuture, 1.second) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment