[英]It's really necessary .addOnCompleteListener when you're using .setPersistenceEnabled(true) on Firebase?
感謝您的好奇心!
我addOnCompleteListener
在使用setPersistence(true)
時是否真的有必要調用addOnCompleteListener
。
當我使用addOnCompleteListener
,如果我的Internet處於脫機狀態,則屏幕將繼續加載,因為addOnCompleteListener
將永遠不會結束-等待連接。 因此,我無法離線添加任何內容,因為加載屏幕正在等待連接(破壞了持久性的概念)。
以下示例顯示了我在說什么:
getDatabaseReference()
.child("Example")
.child(userID)
.push()
.setValue(dataExample)
.addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
if (task.isSuccessful()){
//interface call with success response
interface.onSuccess();
}else {
//interface call with failure response
interface.onFailure(task.getException().getMessage());
}
}
});
因此,正如我所說,如果我的Internet處於離線狀態,我將無法完成操作,因此加載屏幕會永遠加載(等待completelistener)。
我發現,沒有addOnCompleteListener
,我可以在脫機時添加和刪除值,因為它們在緩存中,所以當我有互聯網時,該應用程序會將更新在線發送到數據庫中-很棒。
下面的示例顯示了我的建議:
getDatabaseReference()
.child("Example")
.child(userID)
.push()
.setValue(dataExample);
//interface call with successful response without handling error (because it won't happen)
interface.onSuccess();
所以,我的問題是,這樣做正確嗎? 這是一個好習慣嗎? 如果沒有addOnCompleteListener
,並且可以脫機使用我的應用程序,則僅在有能力時發送更新?
您所看到的是預期的行為。 直到對RealtimeDatabase的寫入到達服務器並且對其他客戶端可見之后,才認為它是“完成”的。 在SDK設法同步之前,本地緩存的寫入才被認為是完整的。 如果您不需要知道服務器最終何時接收到寫操作或寫操作是否成功,則無需在其生成的Task中注冊偵聽器。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.