简体   繁体   中英

It's really necessary .addOnCompleteListener when you're using .setPersistenceEnabled(true) on Firebase?

thanks for curiosity !

I'm in doubt if it's really necessary to call addOnCompleteListener when I'm using setPersistence(true) .

When I use addOnCompleteListener , if my internet is offline, the screen keep loading because the addOnCompleteListener will never end - waiting for connection. So, I can't add anything offline because the loading screen is waiting for connection (breaking the concept of persistence).

Example below shows what I'm talking about :

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());
        }
    }
});

So, as I said, if my internet is offline, I can't complete the action, the loading screen keeps loading forever (waiting for completelistener).

I figured out, that without addOnCompleteListener , I can add and remove values while I'm offline, because they're in cache, so when I have internet, the app send the updates to database online - that's brilliant.

The example below shows what I am proposing:

 getDatabaseReference()
        .child("Example")
        .child(userID)
        .push()
        .setValue(dataExample);

 //interface call with successful response without handling error (because it won't happen)
 interface.onSuccess();

So, my question is, it's right to do it ? It's a good practice ? Without addOnCompleteListener , and stay able to use my app offline, sending updates only when able to ?

What you are seeing is the expected behavior. A write to RealtimeDatabase isn't considered "complete" until it reaches the server and becomes visible to other clients. A locally cached write is not considered complete, until the SDK manages to synchronize it. If you don't need to know when the write is finally received by the server, or if it was successful, then there is no need to register a listener with the Task it generates.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM