Skip to content

Instantly share code, notes, and snippets.

@joseronierison
Last active July 9, 2018 14:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save joseronierison/8cb204e857aa30bf792b7803e6b8d6c6 to your computer and use it in GitHub Desktop.
Save joseronierison/8cb204e857aa30bf792b7803e6b8d6c6 to your computer and use it in GitHub Desktop.
Future for comprehension sample
val user: User = User("user-x")
def getUserProfile(user): Future[UserProfile] = ???
def getUserPermissions(user): Future[UserPermissions] = ???
def getMetrics(user): Future[String] = ???
//Even if the parsing throws an exception, it is handled with Try monad then always return something compositional
def parseMetrics(metrics: String): Try[List[Metrics]] = {
Try(parseJsonFromAnyLib(metrics))
}
//Find only the access metrics and return a future
def getOnlyAccessMetrics(metrics: Future[String]): Future[AccessMetrics] = {
metrics
.flatMap(_ => Future.fromTry(parseMetrics(_)))
.flatMap(metric => metric.find(_.name == "access"))
}
//Aggregate informaiton in a single class (DDD aggregation)
def aggregateUserInfo(profile: UserProfile, userPermissions: UserPermissions, metrics: Metrics): UserInfoAggregate = ???
// This is an for-comprehension, a syntax sugar for flatMaps
// The following future will be completed only all the request are done
val userInfoAggregate: Future[UserInfoAggregate] = for {
profile <- getUserProfile(user) //If it fails, the sequence is stopped
permissions <- getUserPermissions(user) //If it fails, the sequence is stopped
metrics <- getMetrics(user) //At any time I can compose the functions since they alwayre return futures.
} yield aggregateUserInfo(profile, permissions, metrics)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment