Step #5: Reacting to Errors

Now we can have RosterListFragment react to those errors and show the dialog.

First, though, we need a title and message to display in the dialog. Add these two string resources to res/values/strings.xml:

  <string name="import_error_title">Import Failure</string>
  <string name="import_error_message">Something went wrong with the import!</string>

Next, in RosterListFragment, add this handleImportError() function:

  private fun handleImportError() {
    findNavController().navigate(
      RosterListFragmentDirections.showError(
        getString(R.string.import_error_title),
        getString(R.string.import_error_message),
        ErrorScenario.Import
      )
    )
  }

This uses the Navigation component to navigate to the ErrorDialogFragment, using RosterListFragmentDirections and its code-generated showError() function. We pass showError() our two new strings plus ErrorScenario.Import.

Then, add this block of code to the bottom of onViewCreated() in RosterListFragment:

    viewLifecycleOwner.lifecycleScope.launchWhenStarted {
      motor.errorEvents.collect { error ->
        when (error) {
          ErrorScenario.Import -> handleImportError()
        }
      }
    }

This observes the new errorEvents SharedFlow from our motor and, when we receive an Import error, calls handleImportError(). This structure sets us up to be able to handle other types of ErrorScenario, if and when we add any.


Prev Table of Contents Next

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