Skip to content

Commit

Permalink
Add try-finally block to make sure we release the concurrency permit
Browse files Browse the repository at this point in the history
Thanks @objcode
  • Loading branch information
chrisbanes committed Apr 4, 2019
1 parent ee8d7de commit 97e05d4
Showing 1 changed file with 7 additions and 4 deletions.
11 changes: 7 additions & 4 deletions base/src/main/java/app/tivi/extensions/CoroutineExtensions.kt
Original file line number Diff line number Diff line change
Expand Up @@ -20,16 +20,19 @@ import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.launch

suspend fun <A, B> Collection<A>.parallelForEach(
suspend fun <A> Collection<A>.parallelForEach(
concurrency: Int = 10,
block: suspend (A) -> B
block: suspend (A) -> Unit
): Unit = coroutineScope {
val semaphore = Channel<Unit>(concurrency)
forEach { item ->
launch {
semaphore.send(Unit) // Acquire concurrency permit
block(item)
semaphore.receive() // Release concurrency permit
try {
block(item)
} finally {
semaphore.receive() // Release concurrency permit
}
}
}
}

0 comments on commit 97e05d4

Please sign in to comment.