How to make sure that WorkManager cancels my Worker?
Asked Answered
P

1

5

It's mentioned in WorkManager documentation that cancelling a Worker is best-effort

WorkManager makes its best effort to cancel the task, but this is inherently uncertain--the task may already be running or finished when you attempt to cancel it

What if i have a use case that it's mandatory that the Worker gets cancelled upon calling one of the cancelling methods?

Portis answered 25/12, 2018 at 18:28 Comment(0)
I
4

As you wrote WorkManager can only try with a best-effort to cancel a work. In particular, if a task is scheduled to run, and you cancel it, WorkManager will remove it from the schedule.

However, if the tasks it's already running, WorkManager cannot safely interrupt it. The best option is that you write your Worker class taking care of an external cancellation. This has been covered in the Working with WorkManager talk (around minute 15) recorded at the Android Developer Summit 2018.

To be a good citizen you can pool WorkManager using the method: ListenableWorker.isStopped(). You can combine this with the onStopped callback to cleanup your code when you or the OS request to stop the task.

Intermingle answered 27/12, 2018 at 17:12 Comment(1)
Thanks a lot, i watched the video and looks like this is the best approach to handle cancelling for now.Portis

© 2022 - 2024 — McMap. All rights reserved.