Skip to content

Instantly share code, notes, and snippets.

@petrovg
Created March 18, 2015 16:41
Show Gist options
  • Select an option

  • Save petrovg/7e13a7d2e07564dfdacb to your computer and use it in GitHub Desktop.

Select an option

Save petrovg/7e13a7d2e07564dfdacb to your computer and use it in GitHub Desktop.
Scala - Getting future result optionally and combining it with previous future result.
//
// 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