Very simple question. Dashboard screen has a Text,...
# compose
a
Very simple question. Dashboard screen has a Text, viewModel get data from db and so change string in Text.
Copy code
@Composable
fun DashBoardScreen(viewModel: DashBoardViewModel) {

    var dashBoardState = viewModel.uiState.collectAsState().value
    Text(text = "Title ${dashBoardState.title}" )
viewModel.loadData()

// ViewModel
val uiState = MutableStateFlow(DashboardState(false))

   private fun loadData() {
     uiState.value = uiState.value.copy(
            title = "Text Changed" )
    }
i don’t know why Text doesn’t change string…
l
I think you should remove the
.value
at val dashboardState = viewmodel...
a
no doesn’t work
ok how can you change value text in compose screen from viewModel?
l
You have multiple alternatives... The most straightforward is having a livedata to observe as state from your composable
Copy code
@Composable
fun Screen(viewModel: DashBoardViewModel = viewModel()){
   val uiState = viewModel.uiState.observeAsState()
   Text("Title: ${uiState.title}")
}
also, you are using flows, and the way to "change" a flow is emitting values to it
a
i’d like use flow
l
you can not just override its value
its okay, you can use flows, but in order to do so, you must use emit
a
ok do you have some example 🙂 ?
l
I haven't use stateflow much, but maybe something like this? (perhaps someone may correct me)
Copy code
// inside your viewmodel
var x: MutableStateFlow<Int> = MutableStateFlow(0)

fun emitOne(){
   viewModelScope.launch { x.emit(1) }
}
a
thanks
l
hope that helps
d
It's fine to write to a StateFlow using .value too
z
MutableStateFlow
has a writable var property that’s meant to be written to – you don’t need to
emit
on a state flow, and i don’t think it makes any sense to do so. If that’s the behavior you need, you want
MutableSharedFlow
, not
MutableStateFlow
. And as to whether to use
.value
after
collectAsState
or not, if you’re reading the value in the composition anyway, as is being done in this case, it doesn’t matter as far as compose is concerned. The only thing about the code in the OP that looks wrong to me is that it calls
viewModel.loadData()
directly in the composition. That is a side effect, and should be done in an effect handler (e.g.
LaunchedEffect
). But I don’t see how that would be causing the text not to update. It looks like you posted a snippet of your actual code, and I’m guessing something else is wrong that’s causing the issue.
l
Thanks for clarifying ! 👍 also I think Zach is right, something else should be causing the text not updating 🤔