Last active
April 27, 2021 08:51
-
-
Save cjgaliana/b502ebb90c64962a20573d932bd28ce3 to your computer and use it in GitHub Desktop.
Kotlin Await All Parallel
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.cjgaliana.snippets | |
import kotlinx.coroutines.Deferred | |
import kotlinx.coroutines.awaitAll | |
suspend fun <T> Collection<Deferred<T>>.awaitAll(parallelLimit: Int): List<T> { | |
if(this.isEmpty()) { | |
return emptyList() | |
} | |
val result = mutableListOf<T>() | |
val batches = this.chunked(parallelLimit) | |
batches.forEach { deferredTasks -> | |
val batchResults = deferredTasks.awaitAll() | |
result.addAll(batchResults) | |
} | |
return result | |
} | |
// Usage | |
// Create a coroutine scope (in case you don't have one like viewModelScope) | |
private val coroutineScope = CoroutineScope(dispatcherProvider.IO + SupervisorJob()) | |
// Define the Async Function that returns a deferred task | |
// You need to start the func with CoroutineStart.LAZY | |
private fun myFuctionAsync(): Deferred<String> { | |
// Returns a lazy deferred task so we can run these in parallel | |
return coroutineScope.async(start = CoroutineStart.LAZY) { | |
// My code that returns a String | |
} | |
} | |
// Get a list of deferred tasks and execute them in parallel | |
val result = deferredData.awaitAll(parallelLimit) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment