Skip to content

Instantly share code, notes, and snippets.

@PatilShreyas
Last active March 31, 2022 18:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save PatilShreyas/4a4a455dd241183ba5c6b11908f03029 to your computer and use it in GitHub Desktop.
Save PatilShreyas/4a4a455dd241183ba5c6b11908f03029 to your computer and use it in GitHub Desktop.
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