Applying coroutines for asynchronous data processing
In this recipe, we are going to implement a generic extension for the Iterable type, which will provide a replacement for the Iterable<T>.map() function. Our implementation of the Iterable<T>.mapConcurrent() function is going to allow data-mapping-operation optimization by running it concurrently with coroutines. Next, we are going to test our concurrent mapping function implementation by employing it to perform a simulation of a time-expensive operation applied to each of the elements of a sample Iterable object.
How to do it...
- 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
Iterablerange elements:
runBlocking...