Last active
July 9, 2018 14:06
-
-
Save joseronierison/8cb204e857aa30bf792b7803e6b8d6c6 to your computer and use it in GitHub Desktop.
Future for comprehension sample
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
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