Step #4: Creating a Stub Worker

Right-click over the com.commonsware.todo.repo package in the java/ directory and choose “New” > “Kotlin File/Class” from the context menu. For the name, fill in ImportWorker, and choose “Class” for the kind. Press Enter or Return to create the class. Then, replace the class declaration with:

package com.commonsware.todo.repo

import android.content.Context
import androidx.work.CoroutineWorker
import androidx.work.WorkerParameters

class ImportWorker(context: Context, params: WorkerParameters) :
  CoroutineWorker(context, params) {

  override suspend fun doWork() = TODO()
}

A “worker” wraps up our code that will do the work as requested by WorkManager. So, ImportWorker will arrange to import our to-do items from our server.

Specifically, ImportWorker extends CoroutineWorker. A CoroutineWorker is a worker that knows how to integrate with coroutines. We override a doWork() function that does the work that we want. doWork() is a suspend function, and WorkManager can arrange to do that work on a background thread using ordinary coroutines. The CoroutineWorker constructor needs a Context and a WorkerParameters — the latter contains information about the work that we are to perform and is used in advanced WorkManager scenarios.

Right now, our ImportWorker would crash if we ran it, courtesy of the TODO() function. We will fix that shortly.


Prev Table of Contents Next

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