我怎么知道要使用OnComplete还是OnSuccess? [英] How do I know whether to use OnComplete or OnSuccess?

查看:101
本文介绍了我怎么知道要使用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中的许多操作,我可以在OnCompleteListenerOnSuccessListener之间进行选择,并且我想知道如何在它们之间进行选择?.

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 ,但从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:

  1. Use和OnCompleteListenerif(task.isSuccessful()) { ... } else {...}-这将成功代码和失败代码放在一起,如果这些例程共享状态,则可能很有用.
  2. 使用单独的OnSuccessListenerOnFailureListener-这使您可以编写具有更多内聚力的侦听器,因为每个处理程序都专门处理一件事.当然,一个类可以实现两个接口,这为您提供了另一种让它们看到相同状态的方法.
  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.

这篇关于我怎么知道要使用OnComplete还是OnSuccess?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆