- Implement an extension function for the generic Iterable<T> class responsible for handling the mapping operation of its elements concurrently:
suspend fun <T, R> Iterable<T>.mapConcurrent(transform: suspend (T) -> R) =
this.map {
async { transform(it) }
}.map {
it.await()
}
- Simulate time-consuming mapping operations applied to the sample Iterable range elements:
runBlocking {
(0..10).mapConcurrent {
delay(1000)
it * it
}
}
- Print the mapped elements to the console:
runBlocking {
(0..10).mapConcurrent {
delay(1000)
it * it
}.map { println(it) }
}
- Measure the total time of the concurrent-mapping operation's execution and log it to the console:
runBlocking {
val totalTime = measureTimeMillis {
(0..10).mapConcurrent {
delay(1000)
it * it
}.map { println(it) }
}
println("Total time: $totalTime ms")
}
..................Content has been hidden....................
You can't read the all page of ebook, please click
here login for view all page.