https://kotlinlang.org logo
Title
s

S.

04/13/2022, 9:19 PM
I have a list used in a
LazyColumn
and a corresponding add function in the viewmodel but no matter what I try the list does not refresh itself. basically the same code is used for a search feature which works fine. only difference it's not called from a
onClick
but from
onValueChanged
Screen:
val decks by viewModel.decks.collectAsState()
ViewModel
private val _decks = MutableStateFlow(Client.userDecks.value)
    val decks: StateFlow<List<Deck>> = _decks

    suspend fun addDeck(deck: NewDeck) {
        Client.addDeck(deck)
        _decks.value = Client.userDecks.value
    }

    suspend fun filterDecks(input: String) {
        _decks.value = Client.userDecks.value.filter { bla bla }
    }
also checked with printing
_decks.value
and it does contain the added value. forcing the list to recompose by switching screens etc also shows the new value
a

Albert Chang

04/14/2022, 12:49 AM
What is
Client.userDecks
?
s

S.

04/14/2022, 12:51 AM
StateFlow<List<Deck>>
, Deck being a custom data class
a

Albert Chang

04/14/2022, 12:52 AM
What does
Client.addDeck()
do?
s

S.

04/14/2022, 12:56 AM
POST api call and then adding given deck to userDecks as well
well, actually to the
MutableStateFlow
of it. just checked
private val myDecks = MutableStateFlow<MutableList<Deck>>(mutableListOf())
val userDecks: StateFlow<List<Deck>> = myDecks
s

S.

04/14/2022, 12:59 AM
I will check it tomorrow, seems promising ty
👍 1
I'm using the StateFlow inside Client for a superordinate side menu that's supposed to always show, hence my rather scuffed code there. we'll see
m

Michael Paus

04/14/2022, 9:28 AM
Probably not directly related to your problem but this line in your ViewModel
val decks: StateFlow<List<Deck>> = _decks
should more correctly be
val decks: StateFlow<List<Deck>> = _decks.asStateFlow()
:thank-you: 1
s

S.

04/14/2022, 11:01 AM
So the issue was indeed the mutable, ty again. (also makes totally sense) but shouldn't
asStateFlow()
be the same as writing the type explicitly?
m

Mitchell Syer

04/14/2022, 2:20 PM
asStateFlow blocks even casts from working. If you just write the type explicitly then it can be casted to a MutableStateFlow again.
:yes: 1
:thank-you: 1