我在我的安卓应用程序中使用firestore。
在下面的代码中,我可以期望异常为非空吗?
FirebaseFirestore.getInstance().collection("items").document("abc").get().addOnCompleteListener(task -> {
if (!task.isSuccessful()) {
Exception e = task.getException();
//Can I expect e to be non null, or do I have to check for null?
}
});
如果使用 OnCompleteListener,则可以保证具有结果或异常。 如果task.isSuccessful()
,则保证有一个结果对象,没有例外。
addOnCompleteListener(task -> {
if (!task.isSuccessful()) {
// Exception is guaranteed to be non-null
Exception e = task.getException();
}
else {
// Result is guaranteed to be non-null
task.getResult();
}
});
如果使用 OnSuccessListener
,则保证结果为非 null,但如果出现错误,则不会调用。
如果使用 OnFailureListener
,则保证异常为非 null,但如果没有错误,则不会调用异常。
如果您不想在OnCompleteListener
内检查成功,则可以链接OnSuccessListener
和OnFailureListener
。
您可以在本博客系列中阅读我对任务的规范参考。
根据 OnComplete 方法中的任务文档,是的,它必须不为 null。
返回导致任务失败的异常。如果任务尚未完成或未成功完成,则返回 null。链接 - https://developers.google.com/android/reference/com/google/android/gms/tasks/Task.html#getException((