https://kotlinlang.org logo
#coroutines
Title
# coroutines
t

Tim Malseed

06/08/2021, 4:40 AM
I've got a couple of 
StateFlows
 the second depends on the first. But, the second is not emitting when I expect it to..
Copy code
private val playlist = playlistRepository.getPlaylists(PlaylistQuery.PlaylistId(initialPlaylist.id))
        .map { playlists ->
            playlists.firstOrNull()
        }
        .filterNotNull()
        .stateIn(
            scope = this,
            started = SharingStarted.WhileSubscribed(),
            initialValue = initialPlaylist
        )

    private val playlistSongs: StateFlow<List<PlaylistSong>> = playlist
        .flatMapConcat { playlist ->
            playlistRepository.getSongsForPlaylist(playlist.id, playlist.sortOrder)
        }
        .stateIn(
            scope = this,
            started = SharingStarted.WhileSubscribed(),
            initialValue = emptyList()
        )
playlistSongs
 depends on 
playlists
. When 
playlist
 is re-emitted, I expect 
playlistSongs
 to flatmap the new 
playlist
, and potentially emit a new set of playlistSongs But the 
flatMapConcat
 block in 
playlistSongs
 doesn't seem to get called, even after 
playlist
 emits. Both flows are collected in 
bindView()
 (called in 
Fragment.onViewCreated()
 :
Copy code
override fun bindView(view: PlaylistDetailContract.View) {
    super.bindView(view)

    launch {
        playlist.collect { playlist ->
            foo()
        }
    }
    launch {
        playlistSongs.collect { playlistSongs ->
            bar()
        }
    }
}
m

mateusz.kwiecinski

06/08/2021, 4:47 AM
When 
playlist
 is re-emitted
by
re-emitted
you mean exactly the same value gets emitted?
t

Tim Malseed

06/08/2021, 4:47 AM
No. The
playlist
object is a new instance and not equal.
playlistRepository.getSongsForPlaylist()
is not called even though
playlist
emits a new, not-equal
playlist
.
m

mateusz.kwiecinski

06/08/2021, 4:49 AM
and does
getSongsForPlaylist
get called for the first time? When first
playlits
value is emitted?
t

Tim Malseed

06/08/2021, 4:49 AM
Yes
m

mateusz.kwiecinski

06/08/2021, 4:50 AM
ok then, my guess would be the
getSongsForPlaylist
called for the first
playlist
emitted never completes
t

Tim Malseed

06/08/2021, 4:51 AM
OK. You're probably right! I need to think this over
m

mateusz.kwiecinski

06/08/2021, 4:51 AM
you probably would like to cancel collecting
getSongsForPlaylist
if a new playlist is emitted
t

Tim Malseed

06/08/2021, 4:53 AM
Do you have any suggestions as to how/where to cancel that?
m

mateusz.kwiecinski

06/08/2021, 4:54 AM
Use
flatMapLatest
instead of
flatMapConcat
💯 1
t

Tim Malseed

06/08/2021, 4:55 AM
Thanks so much! Been trying to figure this one out for a while!
👍 1
2 Views