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?
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.