Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to handle state flow on back navigate on compose

I am following unidirectional flow in compose for ui state so basically i have sealed class as follow

sealed class UiState{
objet Loading:UiState()
object Success:UiState()
object Error(val error:String):UiState()
}

and in viewmodel

 private val _latestUiState= MutableStateFlow<UiState>(UiState.Empty)
    val latestUiState= _latestUiState.asStateFlow()

At first api will call on page startup, and on the basis of response corresponding state will emit. There is no issue on normal case. But suppose there is another button on the page whose function is to navigate to about section of app. At first api will call data, there will be some error and i emit error state. Now if i click button then navigate back same error state will show again.

I know some of you will suggest to use shared flow (one shot emit). But i follow official ways and see some of the sample in github (google official), in this case by using sateflow how can i handle .

Also second question, is there is any way to force compose to recreate new instance of view model on navigate back while using hiltviewmodel with navigation

like image 346
Kartik Avatar asked Nov 23 '25 15:11

Kartik


1 Answers

There is a section about this in the android architecture guide: Consuming events can trigger state updates

Basically, you can make error string nullable, and after you display the message for the first time, you will call some method from your ViewModel and it will set error to null.

For your second question, that would kinda defeat the purpose of ViewModel - what are you trying to solve? There's probably better solution.

like image 69
Jan Bína Avatar answered Nov 25 '25 04:11

Jan Bína