Step #6: Doing the Work

To wrap up our ImportWorker implementation, replace the stub doWork() function with this one:

  override suspend fun doWork() = try {
    repo.importItems(prefs.loadWebServiceUrl())

    Result.success()
  } catch (ex: Exception) {
    Log.e("ToDo", "Exception importing items in doWork()", ex)
    Result.failure()
  }

doWork() now does the same basic thing as our manual import logic in RosterMotor, except that WorkManager provides the CoroutineScope.

doWork() needs to return a Result object. Result.success() and Result.failure() give us Result objects representing those statuses, and so our doWork() returns one depending upon whether or not we had an exception.

So, if WorkManager arranges to call doWork() on our ImportWorker, we will import the to-do items from our server.


Prev Table of Contents Next

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