我怎么知道要使用OnComplete还是OnSuccess?
我试图在线找到答案,但是找不到特定于Firebase
实现的答案.
I tried to find an answer online for it, but I couldn't find one which is specific for Firebase
implementations.
对于Firebase
中的许多操作,我可以在OnCompleteListener
和OnSuccessListener
之间进行选择,并且我想知道如何在它们之间进行选择?.
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?.
我已阅读 OnComplete 和 OnSuccess a>,但从Firebase文档中可以看到,这一个,例如,对于一个特定的操作(如示例中的get
操作),它们有时使用OnSuccessListener
,有时则使用OnCompleteListener
.
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.
顾名思义,onSuccess()
将在任务成功完成时触发.
As the name suggests, onSuccess()
will fire when a task is completed successfully.
onComplete()
将在任务完成时触发,即使它失败了.
onComplete()
will fire when the task is completed, even if it failed.
在该方法中,您可以调用Task.isSuccessful()
和Task.getException()
.
In the method, you can call Task.isSuccessful()
and Task.getException()
.
在onSuccess()
中,您可以确定isSuccessful()
将返回true,而getException()
将返回null(因此调用它们没有多大意义).
In onSuccess()
you can be certain that isSuccessful()
will return true, and getException()
will return null (so there's not much point calling them).
在onComplete()
中isSuccessful()
可能是false
,您有机会处理故障,也许使用getException()
来获取更多详细信息.
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和
OnCompleteListener
和if(task.isSuccessful()) { ... } else {...}
-这将成功代码和失败代码放在一起,如果这些例程共享状态,则可能很有用. - 使用单独的
OnSuccessListener
和OnFailureListener
-这使您可以编写具有更多内聚力的侦听器,因为每个处理程序都专门处理一件事.当然,一个类可以实现两个接口,这为您提供了另一种让它们看到相同状态的方法.
- 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.