Search code examples
android-workmanager

How can I execute cleanup code in my CoroutineWorker when onStopped is final?


I upgraded to WorkManager 2.1.0 and tried to use some of the Kotlin extensions including CoroutineWorker. My worker was extending androidx.work.Worker previously and it was executing cleanup code by overriding onStopped. Why is onStopped final in CoroutineWorker? Is there any other way for me to execute cleanup code after the CoroutineWorker is stopped?

According to this blog post, is this supposed to be a feature?


Solution

  • You can always use job.invokeOnCompletion without having to rely on the onStopped callback for CoroutineWorker. E.g.,

    import android.content.Context
    import android.util.Log
    import androidx.work.CoroutineWorker
    import androidx.work.WorkerParameters
    import kotlinx.coroutines.CancellationException
    import kotlinx.coroutines.async
    import kotlinx.coroutines.coroutineScope
    
    class TestWorker(context: Context, params: WorkerParameters) : CoroutineWorker(context, params) {
    
        companion object {
            private const val TAG = "TestWorker"
        }
    
        override suspend fun doWork(): Result {
            return coroutineScope {
                val job = async {
                    someWork()
                }
    
                job.invokeOnCompletion { exception: Throwable? ->
                    when (exception) {
                        is CancellationException -> {
                            Log.e(TAG, "Cleanup on completion", exception)
                            // cleanup on cancellations
                        }
                        else -> {
                            // do something else.
                        }
                    }
                }
    
                job.await()
            }
        }
    
        suspend fun someWork(): Result {
            TODO()
        }
    }