Junior — Middle
How can you cancel a task launched via WorkManager?
sobes.tech AI
Answer from AI
To cancel a task launched via WorkManager in Android, you can use the cancellation methods provided by WorkManager itself. The main ways to cancel:
- Cancel by task ID (UUID):
val workManager = WorkManager.getInstance(context)
workManager.cancelWorkById(workRequest.id)
- Cancel by tag, if the task was started with a tag:
workManager.cancelAllWorkByTag("myTag")
- Cancel by chain name:
workManager.cancelUniqueWork("uniqueWorkName")
After calling the cancel method, WorkManager will attempt to stop the task if it has not yet completed. It is important that the task itself (Worker) implements proper cancellation handling, such as checking the isStopped flag and exiting the work promptly.
Example inside Worker:
class MyWorker(context: Context, params: WorkerParameters) : Worker(context, params) {
override fun doWork(): Result {
for (i in 0 until 100) {
if (isStopped) {
return Result.failure()
}
// Perform part of the work
}
return Result.success()
}
}