The Barrier design pattern provides us with the means to wait for multiple concurrent tasks before proceeding further. A common use case is composing objects from different sources.
Take, for example, the following class:
data class FavoriteCharacter(val name: String, val catchphrase: String, val repeats: Int)
Assume that we're fetching name, catchphrase, and number. This catchphrase is being repeated from three different sources.
The most basic way would be to use CountDownLatch, as we did in some of the previous examples:
val latch = CountDownLatch(3)
var name: String? = null
launch {
delay(Random().nextInt(100))
println("Got name")
name = "Inigo Montoya"
latch.countDown()
}
var catchphrase = ""
launch {
delay(Random().nextInt(100))
println("Got catchphrase")
catchphrase = "Hello. My name is Inigo Montoya...