will this work as expected? trying to make and awa...
# coroutines
b
will this work as expected? trying to make and await all calls in parallel; typeSafeUpdate is a suspend function, awaitAll() is a suspend function
Copy code
suspend fun stop(game: Game, weatherEffect: WeatherEffect) = coroutineScope {
    val playlists = async {
        findPlayingWeatherPlaylist(game)
            .map { it.stopAll() }
            .awaitAll()
    }
    val sounds = async {
        findPlayingWeatherSound(game)
            .forEach { it.typeSafeUpdate { playing = false } }
    }
    playlists.await()
    sounds.await()
}
my general gutt feeling is that the foreach will not be executed in parallel
1
c
I'm not exactly sure what you're expecting, but as far as I can see,
playlists
and
sounds
will be executed in parallel to each other.
What is the return type of
stopAll
? It looks like it returns some kind of
Deferred
, but shouldn't it be
suspend
instead?
b
stopAll() returns a deferred yes (mapped from a Promise to run List.awaitAll())
so I'm pretty sure everything in playlists is fired all at once
but I'm unsure if the sounds block will fire off each typeSafeUpdate in parallel
c
What is the return type of
findPlayingWeatherSound
?
If it's
List
,
Sequence
or
Flow
, then yeah,
typeSafeUpdate
s are called sequentially to each other (but in parallel to everything happening to the playlists)
b
it's a list, is there a way to do that in parallel?
wrap the insides of forEach in another async, replace forEach with map and place awaitAll at the end?
val sounds = async { findPlayingWeatherSounds(game, effectsToStop) .map { async { it.typeSafeUpdate { playing = false } } } .awaitAll() }
c
yes, that's the simplest way
❤️ 1
If you don't mind using Arrow FX, you can write:
Copy code
findPlayingWeatherSounds(game, effectsToStop)
    .parMap { it.typeSafeUpdate { playing = false } }
but it's just a shortcut for the same code, it doesn't change anything.
z
If you don’t need the result of typeSafeUpdate then you can use launch instead of async.
1