How do I know whether to use OnComplete or OnSuccess?

As the name suggests, onSuccess() will fire when a task is completed successfully.

onComplete() will fire when the task is completed, even if it failed.

In the method, you can call Task.isSuccessful() and Task.getException().

In onSuccess() you can be certain that isSuccessful() will return true, and getException() will return null (so there's not much point calling them).

In onComplete() isSuccessful() may be false, and you have the opportunity to deal with the failure, perhaps using getException() to obtain more detail.

If you need to handle failed tasks (and you should!), you have two choices:

  1. Use and OnCompleteListener, and if(task.isSuccessful()) { ... } else {...} -- this puts the success and failure code close together, and may be useful if those routines share state.
  2. Use separate OnSuccessListener and OnFailureListener -- this allows you to write listeners with a bit more cohesion, in that each handler specialises in one thing. Of course, one class may implement both interfaces, giving you another way to have both see the same state.

To add to what slim answered above in my use of Firebase. I find out that this two listeners (OnCompleteListener and OnSuccessListener)

Have different callback times in writing data to their servers.

The general rule of thumb

If you're relying on a systematic(sequential) way of writing to the servers in order to perform some logic then use OnCompleteListener

If you're not dependent on a systematic(non-sequential i.e async tasks) way of writing to the servers in order to perform some logic then use OnSuccessListener

Tags:

Java

Firebase