Skip to content

Instantly share code, notes, and snippets.

@derekjw
Created February 8, 2012 01:51
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save derekjw/1764249 to your computer and use it in GitHub Desktop.
Save derekjw/1764249 to your computer and use it in GitHub Desktop.
Future flatMap example
class HttpClient {
def get(uri: URI): Future[String]
}
// return Future of next URI to get
def getUri(): Future[URI]
// return's available HttpClient from a pool
def getHttpClient(): Future[HttpClient]
// returns a Tuple of the URI and the client's result
getURI() flatMap { uri =>
getHttpClient() flatMap { httpClient =>
httpClient get uri map (result => (uri -> result))
}
}
// The same as above, but as a for-comprehension
for {
uri <- getURI()
httpClient <- getHttpClient()
result <- httpClient get uri
} yield (uri -> result)
// kinda Java
class HttpClient {
def get(uri: URI): Future[String]
}
Future<URI> getUri() { ... }
Future<HttpClient> getHttpClient() { ... }
Mapper<String, Tuple2<URI, String>> formatResult(URI uri) {
new Mapper<String, Tuple2<URI, String>>() {
Tuple2<URI, String> apply(String str) {
new Tuple2(uri, str)
}
}
}
Mapper<HttpClient, Future<Tuple2<URI, String>>> clientGetResult(URI uri) {
new Mapper<String, Future<Tuple2<URI, String>>>() {
Future<Tuple2<URI, String>> apply(HttpClient httpClient) {
httpClient.get(uri).map(formatResult(uri))
}
}
}
Mapper<URI, Future<Tuple2<URI, String>>> uriGetResult() {
new Mapper<URI, Future<Tuple2<URI, String>>>() {
Future<Tuple2<URI, String>> apply(URI uri) {
getHttpClient().flatMap(clientGetResult(uri))
}
}
}
getURI().flatMap(uriGetResult())
//without generics
Mapper formatResult(URI uri) {
new Mapper() {
Tuple2 apply(String str) {
new Tuple2(uri, str)
}
}
}
Mapper clientGetResult(URI uri) {
new Mapper() {
Future apply(HttpClient httpClient) {
httpClient.get(uri).map(formatResult(uri))
}
}
}
Mapper uriGetResult() {
new Mapper() {
Future apply(URI uri) {
getHttpClient().flatMap(clientGetResult(uri))
}
}
}
getURI().flatMap(uriGetResult())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment