CoroutineWorker: Use Kotlin Coroutines in WorkManager

May 13, 2019

Use CoroutineWorker.

Dependencies

depedencies {
    // https://mvnrepository.com/artifact/androidx.work/work-runtime-ktx
    def work_version = '2.0.1'
    // use -ktx for Kotlin+Coroutines
    implementation "androidx.work:work-runtime-ktx:$work_version"
}

Code

class ReminderWorker(appContext: Context, workerParams: WorkerParameters): CoroutineWorker(appContext, workerParams), LifecycleOwner {
    companion object {
        fun run() : LiveData<WorkInfo> {
            val work = OneTimeWorkRequestBuilder<ReminderWorker>().build()
            WorkManager.getInstance().enqueue(work)

            return WorkManager.getInstance().getWorkInfoByIdLiveData(work.id)
        }
    }


    override suspend fun doWork(): Result = coroutineScope {
        val worker = this@ReminderWorker

        // test coroutines
        val d = async {
            delay(1000)
            "hello"
        }
        val value = d.await()

        Result.success()
    }
}
This work is licensed under a
Creative Commons Attribution-NonCommercial 4.0 International License.