2

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

Kartik
  • 21
  • 1

1 Answers1

1

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.

Jan Bína
  • 3,447
  • 14
  • 16
  • (second question with details): I have a long form (>20 fields), after valid entry it will redirect to new page, but after navigate back, as expected, form field value will be shown, but as per my requirements form should be reset. Here I can reset value of each field, but i am thinking if i create new instance there is no need of writing code for resetting 20 field :). Is there any better way to do this? – Kartik Jan 09 '23 at 04:24
  • I'd definitely keep the ViewModel, creating new instance after back navigation and not in other cases would be tedious, and in future, you might want to keep some state even after navigating back. I'd reset the form before navigating away from the form screen as you suggest. To make it less verbose, you can encapsulate everything that has to be reset into one class and do something like `uiState = uiState.copy(formState = FormState())` – Jan Bína Jan 09 '23 at 11:01