How do I know whether to use OnComplete or OnSuccess?
Solution 1
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:
- Use and
OnCompleteListener
, andif(task.isSuccessful()) { ... } else {...}
-- this puts the success and failure code close together, and may be useful if those routines share state. - Use separate
OnSuccessListener
andOnFailureListener
-- 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.
Solution 2
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
Solution 3
Sometimes you may find that you need to use value of the result say for example getting device token.. only the onSuccess will give InstanceIdResult and not onComplete... so therefore you must use onSuccess...
// Get The Device Token And Put It Into Firebase Instance
FirebaseInstanceId.getInstance().getInstanceId().addOnSuccessListener(new OnSuccessListener<InstanceIdResult>() {
@Override
public void onSuccess(InstanceIdResult instanceIdResult) {
String DeviceToken = instanceIdResult.getToken();
}
});
![Tal Barda](https://i.stack.imgur.com/5PdRu.jpg?s=256&g=1)
Comments
-
Tal Barda about 2 years
I tried to find an answer online for it, but I couldn't find one which is specific for
Firebase
implementations.I can choose between
OnCompleteListener
andOnSuccessListener
for a lot of operations inFirebase
, and I'd like to know how can I choose between them?.I have read the documentation for OnComplete and OnSuccess, but as I can see from Firebase documentations, this one for example, for one specific operation (like
get
operation in the example), they sometimes useOnSuccessListener
and sometimes they useOnCompleteListener
.How can I know which one is better in every situation? Does it matter? Considering that I'd like to know for every operation if it was succussful or not.