Compile with gradlew build and run gradlew run
Comparing the use of foreach loop without lambdas and the use of a pipeline
(such as ....asSequence().map(...).reduce(...)) with lambdas and the resulting
sequential versus concurrent behavior.
suspend fun fetchAndSum(vararg urls: String): Int {
var sum = 0
for (url in urls) {
println("FETCHING from $url")
val resp = httpClient
.sendAsync(request(url), BodyHandlers.ofString())
.await()
println("=======> from $url")
sum = sum + resp.body().length
}
return sum
} |
suspend fun CoroutineScope.fetchAndSumλ(vararg urls: String): Int {
return urls
.asSequence()
.map { url -> async {
println("FETCHING from $url")
val resp = httpClient
.sendAsync(request(url), BodyHandlers.ofString())
.await()
println("=======> from $url")
resp.body().length
}}
.reduce { prev, curr -> async {
prev.await() + curr.await()
}}
.await();
} |
|
|