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
and OnSuccessListener
for a lot of operations in Firebase
, 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 use OnSuccessListener
and sometimes they use OnCompleteListener
.
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.
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:
OnCompleteListener
, and if(task.isSuccessful()) { ... } else {...}
-- this puts the success and failure code close together, and may be useful if those routines share state.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
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();
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With