CoroutineWorker: Use Kotlin Coroutines in WorkManager

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()    }}

❤️ Is this article helpful?

Buy me a coffee ☕ or support my work via PayPal to keep this space 🖖 and ad-free.

Do send some 💖 to @d_luaz or share this article.

✨ By Desmond Lua

A dream boy who enjoys making apps, travelling and making youtube videos. Follow me on @d_luaz

👶 Apps I built

Travelopy - discover travel places in Malaysia, Singapore, Taiwan, Japan.