Barrier
The Barrier design pattern enables us to pause and wait for multiple concurrent tasks to finish before moving on. This is particularly useful when assembling objects from diverse data sources.
Consider this data
class:
data class FavoriteCharacter(
val name: String,
val catchphrase: String,
val picture: ByteArray = Random.nextBytes(42)
)
Imagine the catchphrase comes from one service, and the picture comes from another. You’d like to fetch both data points concurrently:
fun CoroutineScope.getCatchphraseAsync(characterName: String) = async { … }
fun CoroutineScope.getPictureAsync(characterName: String) = async { … }
The most straightforward way to fetch this data concurrently would look like this:
suspend fun fetchFavoriteCharacter(name: String) = coroutineScope {
val catchphrase = getCatchphraseAsync(name).await()
val picture = getPictureAsync(name).await()
FavoriteCharacter(name, catchphrase, picture)...