Skip to content

Instantly share code, notes, and snippets.

@soumyasd
Forked from derekjw/gist:1764249
Last active August 29, 2015 14:24
Show Gist options
  • Save soumyasd/c8246babfb8b3adb4dd5 to your computer and use it in GitHub Desktop.
Save soumyasd/c8246babfb8b3adb4dd5 to your computer and use it in GitHub Desktop.
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