Skip to content

Instantly share code, notes, and snippets.

@PatilShreyas
Last active Mar 31, 2022
Embed
What would you like to do?
fun <T, R> Iterable<T>.map(
concurrency: Int,
transform: (T) -> R
): List<R> = runBlocking {
// Create semaphore with permit specified as `concurrency`
val semaphore = Semaphore(concurrency)
map { item ->
// Before processing each item, acquire the semaphore permit
// This will be suspended until permit is available.
semaphore.acquire()
async(Dispatchers.Default) {
try {
transform(item)
} finally {
// After processing (or failure), release a semaphore permit
semaphore.release()
}
}
}.awaitAll()
}
fun doSomething(users: List<User>) {
// Concurrently 5 users will be processed
users.map(concurrency = 5) { user -> user.toSomething() /* `toSomething()` is heavy method */ }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment