3

When use Tasks.call(Callable), can I cancel it, and remove all the listeners from the task?

Wenhui
  • 648
  • 4
  • 13

2 Answers2

3

If you need a way to remove all the listeners from any Task at any time, you will have to remember all the listeners you previously added, then remove them all manually.

If you're working with an Android app, and you add Activity-scoped listeners, they will be removed automatically when the host activity is stopped (goes through its onStop() lifecycle method). Note that you have to pass the activity as an argument to addOnCompleteListener().

Doug Stevenson
  • 297,357
  • 32
  • 422
  • 441
  • Thank you for your replay. I was hoping there might be an easy way to cancel a Task without override CancellableTask, since overriding CancellableTask, I won't be able to use Tasks.call(). – Wenhui Apr 18 '17 at 17:09
  • @Doug Stevenson Can you elaborate how exactly one can remove the listeners? I cannot see an API for that and addXXXListener on a task does not accept `null`. Moreover I am looking a way to Cancel a task but it appears that the APIs are precisely build to prevent that. It make using Task prone to leaking activities. I understand that there are "Activity-scoped listeners" but there are many scenarios where this is not sufficient. – Ankit Dec 03 '19 at 09:46
2

A Task class doesn't have a function you can call to cancel. You should use it's subclass CancellableTask instead, to be able to use cancel():

public abstract boolean cancel ()

Attempts to cancel the task. A canceled task cannot be resumed later. A canceled task calls back on listeners subscribed to addOnFailureListener(OnFailureListener) with an exception that indicates the task was canceled.

Returns

  • true if this task was successfully canceled or is in the process of being canceled. Returns false if the task is already completed or in a state that cannot be canceled.

If you still insist on using Task instead, I think it'd be best to refer to similar posts that are using AsyncTasks like this one.

Community
  • 1
  • 1
AL.
  • 36,815
  • 10
  • 142
  • 281