0

I am using StateFlow to host UI states and MutableStateFlow as backing property in my ViewModel class. Let's suppose my property is called uiState and initialized as follows:

private var _uiState = MutableStateFlow(SomeData(message="NONE"))
val uiState: StateFlow<SomeData>
        get() = _uiState.asStateFlow()

I know that I can update _uiState by

_uiState.update {it.copy(message="Some message")}

then in my Activity I can collect the data like this:

lifecycleScope.launch {
    repeatOnLifecycle(Lifecycle.State.STARTED) {
        launch { 
            viewModel.uiState.collect { data ->
                // Get data
            }
        }
    }
}

How can I throw errors in my view model and then catch it in the activity?

I mean is that possible to somehow throw errors like this

_uiState.update {
    // Throwing error? How?
}

In my view model and then catch it in the Activity as:

lifecycleScope.launch {
    repeatOnLifecycle(Lifecycle.State.STARTED) {
        launch {
            viewModel.uiState
                .catch {
                    // Catch error
                }
                .collect { data ->
                    // Get data
            }
        }
    }
}

I think when we create a flow using flow {} we can throw errors in the block and then catch it like above code; but what about StateFlow ?

Mahesh Thorat
  • 1
  • 4
  • 11
  • 22
  • I would not throw an error, instead I would create an error state and emit that value. – Umit Apr 14 '23 at 03:55

0 Answers0