CoroutineWorker: Use Kotlin Coroutines in WorkManager

Use CoroutineWorker.


depedencies {
    def work_version = '2.0.1'
    // use -ktx for Kotlin+Coroutines
    implementation "$work_version"


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