Android75
11/29/2022, 7:32 PM@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…Lisandro Di Meo
11/29/2022, 7:45 PM.value
at val dashboardState = viewmodel...Android75
11/29/2022, 7:53 PMAndroid75
11/29/2022, 7:53 PMLisandro Di Meo
11/29/2022, 7:54 PMLisandro Di Meo
11/29/2022, 7:56 PM@Composable
fun Screen(viewModel: DashBoardViewModel = viewModel()){
val uiState = viewModel.uiState.observeAsState()
Text("Title: ${uiState.title}")
}
Lisandro Di Meo
11/29/2022, 7:56 PMAndroid75
11/29/2022, 7:57 PMLisandro Di Meo
11/29/2022, 7:57 PMLisandro Di Meo
11/29/2022, 7:58 PMAndroid75
11/29/2022, 7:59 PMLisandro Di Meo
11/29/2022, 8:02 PM// inside your viewmodel
var x: MutableStateFlow<Int> = MutableStateFlow(0)
fun emitOne(){
viewModelScope.launch { x.emit(1) }
}
Android75
11/29/2022, 8:03 PMLisandro Di Meo
11/29/2022, 8:06 PMdorche
11/30/2022, 4:24 PMZach Klippenstein (he/him) [MOD]
11/30/2022, 11:28 PMMutableStateFlow
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.Lisandro Di Meo
12/01/2022, 2:35 PM