Meet
11/12/2025, 5:38 AMMeet
11/12/2025, 5:41 AMViewModel with a MutableStateFlow that updates UI after a delay.
• When the app is loading for 5 seconds, I switch to another window (so my Compose Desktop app loses focus).
• After 5 seconds (in logs), the UiState updates successfully — I can see:
MainViewModel: Initializing...
MainViewModel: Loading...
MainViewModel: Loaded!
MainViewModel: Context changed!
MainViewModel: Updating message...
MainViewModel: Message set!
MainViewModel: Done!
• But when I return to the app window, it still shows the old loading UI.
• The new state only appears after I resize the window — then the UI suddenly updates and shows the new message.
So, the StateFlow value is updating, but the Compose UI doesn’t recompose until I manually trigger a redraw (e.g., window resize or focus regain).Meet
11/12/2025, 5:41 AMclass MainViewModel : ViewModel() {
private val _uiState = MutableStateFlow(MainUiState())
val uiState= _uiState.asStateFlow()
init {
println("MainViewModel: Initializing...")
viewModelScope.launch {
println("MainViewModel: Loading...")
delay(5000)
println("MainViewModel: Loaded!")
withContext(Dispatchers.Main) {
println("MainViewModel: Context changed!")
println("MainViewModel: Updating message...")
_uiState.update {
MainUiState(
isLoading = false,
message = "Hello from ViewModel 👋"
)
}
println("MainViewModel: Message set!")
}
println("MainViewModel: Done!")
}
}
}
data class MainUiState(
val isLoading: Boolean = true,
val message: String? = null
)
@Composable
fun MainScreen() {
val viewModel = viewModel<MainViewModel>()
val uiState by viewModel.uiState.collectAsState()
Box(
modifier = Modifier
.fillMaxSize()
.padding(16.dp),
contentAlignment = Alignment.Center
) {
if (uiState.isLoading) {
CircularProgressIndicator()
} else {
Text(
text = uiState.message ?: "No message",
)
}
}
}Meet
11/12/2025, 5:43 AMkotlin = "2.2.21"
composeMultiplatform = "1.9.2"
androidx-lifecycle = "2.9.5"
androidx-lifecycle-viewmodel-compose = { module = "org.jetbrains.androidx.lifecycle:lifecycle-viewmodel-compose", version.ref = "androidx-lifecycle" }
androidx-lifecycle-runtime-compose = { module = "org.jetbrains.androidx.lifecycle:lifecycle-runtime-compose", version.ref = "androidx-lifecycle" }Meet
11/12/2025, 5:44 AMgildor
11/12/2025, 6:12 AMMeet
11/12/2025, 6:54 AMval uiState by viewModel.uiState.collectAsStateWithLifecycle()
this work it
val uiState by viewModel.uiState.collectAsStateWithLifecycle(minActiveState = Lifecycle.State.RESUMED)gildor
11/12/2025, 6:56 AMMeet
11/12/2025, 6:59 AMMeet
11/12/2025, 12:59 PMgildor
11/12/2025, 1:03 PMgildor
11/12/2025, 1:04 PMgildor
11/12/2025, 1:05 PMMeet
11/12/2025, 1:09 PMgildor
11/12/2025, 1:10 PMgildor
11/12/2025, 1:11 PMMeet
11/12/2025, 1:11 PMgildor
11/12/2025, 1:42 PMMeet
11/12/2025, 1:43 PMMeet
11/12/2025, 1:43 PMMeet
11/12/2025, 1:49 PMMeet
11/13/2025, 5:51 AMgildor
11/13/2025, 5:52 AMMeet
11/13/2025, 5:53 AMgildor
11/13/2025, 6:41 AM