Setting variable inside onDataChange in Firebase (singleValue Listener)

前端 未结 3 1257
孤街浪徒
孤街浪徒 2020-12-19 15:28

This is just an example of what my code is like. Right now, if I print out the userName variable inside onDataChange, it works fine. But if I try printing userName outside,

相关标签:
3条回答
  • 2020-12-19 16:12

    Firebase event listeners are excuted Asynchrounosly, meaning, it runs in background and when it's done, it notifies you using the callback you provided in your case the ValueEventListener and calls one or more of it's methods onDataChanged or onCancelled.

    That said, printing the userName variable might show a value and might not, depending on whether the callback was triggered before printing it or not.

    So, it's a pretty natural behaviour as code excutes one line at a time.

    0 讨论(0)
  • 2020-12-19 16:20

    This is something I've often found tricky with Firebase. The only real solutions I could suggest would be to make sure that any code where you need to access the Firebase variables is either:

    1) Inside the onDataChange method.

    2) Only called/accessed once the addListenerForSingleValueEvent onDataChange method has completed.

    0 讨论(0)
  • 2020-12-19 16:28

    Listeners in Firebase are asynchronous, so you can not set a variable like that. You should pass a callback function in the function where you have declared your listener.

    This callback function will then take the result from firebase call and do further processing on it.

    public void doSomething(@NotNull final Callback callback) {
    
        final Query query = mDatabase.child(FirebaseConstants.TARGET);
    
        query.addListenerForSingleValueEvent(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                String userName = dataSnapshot.child("userName").getValue(String.class);
                callback.OnComplete(userName);
            }
    
            @Override
            public void onCancelled(DatabaseError databaseError) {
            }
        });
    }
    
    0 讨论(0)
提交回复
热议问题