Step #4: Emitting Errors From the Motor

The point behind the dialog is to tell the user when there is a problem in importing to-do items. That implies that something knows to show the dialog when that occurs. One way to do that is to have the viewmodel tell its activity or fragment about errors. In this case, that would be RosterMotor telling RosterListFragment about errors.

So, add these properties to RosterMotor:

  private val _errorEvents = MutableSharedFlow<ErrorScenario>()
  val errorEvents = _errorEvents.asSharedFlow()

These are similar to the _navEvents/navEvents pair that we set up earlier. However, they emit an ErrorScenario instead.

Then, revise importItems() on RosterMotor to be:

  fun importItems() {
    viewModelScope.launch {
      try {
        repo.importItems(prefs.loadWebServiceUrl())
      } catch (ex: Exception) {
        Log.e("ToDo", "Exception importing items", ex)
        _errorEvents.emit(ErrorScenario.Import)
      }
    }
  }

Now we wrap our importItems() call on ToDoRepository() in a try/catch block. If we get an error from the repository, we log it to Logcat using Log.e() and emit an Import scenario on our new channel.


Prev Table of Contents Next

This book is licensed under the Creative Commons Attribution-ShareAlike 4.0 International license.