How to do it...

  1. 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()
}
  1. Simulate time-consuming mapping operations applied to the sample Iterable range elements:
runBlocking {
(0..10).mapConcurrent {
delay(1000)
it * it
}

}
  1. Print the mapped elements to the console:
runBlocking {
(0..10).mapConcurrent {
delay(1000)
it * it
}.map { println(it) }
}
  1. 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.
Reset
3.20.237.21