Sobes.tech
Junior — Middle

How can an error be displayed in the View based on data received from LiveData?

sobes.tech AI

Answer from AI

To display an error in the View based on data from LiveData, it is common to create a separate LiveData object for errors in the ViewModel. The View subscribes to this LiveData and displays an error message when the data changes.

Example:

// In ViewModel
private val _error = MutableLiveData<String?>()
val error: LiveData<String?> = _error

fun loadData() {
    try {
        // load data
    } catch (e: Exception) {
        _error.value = e.message
    }
}

// In Activity or Fragment
viewModel.error.observe(viewLifecycleOwner) { errorMessage ->
    if (errorMessage != null) {
        // show error, e.g., Toast or TextView
        Toast.makeText(context, errorMessage, Toast.LENGTH_LONG).show()
    }
}

This approach separates error handling logic from the UI and makes it easy to manage error display.

How can an error be displayed in the View based on… - sobes.tech