0

I am trying to set the value of a variable which i have declared globally but when i am setting the value it sets to default ...
Let me show you the code ...

var userWeight:Double = 0.0

Here i am trying to update the userWeight Value but it sets to 0.0 outside of the sucesslistener and inside it the value is correctly updated ...

Here is my log to clarify this better

 getUserDetails().addOnSuccessListener { document->
            userWeight = document.toObject(User::class.java)!!.weight.toDouble()
            Log.d("temperory","$userWeight")
        }

enter image description here

getUserDetails().addOnSuccessListener { document->
            userWeight = document.toObject(User::class.java)!!.weight.toDouble()
            Log.d("temperory","$userWeight")
        }

        Log.d("weightuser","$userWeight")

enter image description here

Jadu
  • 489
  • 3
  • 10
  • Can you elaborate your question? Like are asking why the second log with tag as weightuser is printing weight as 0? – Priyanshu Dec 26 '22 at 09:05
  • No! Actually I have declared a global variable named userWeight but when i am trying to update the value of userWeight inside of the successlistener see the code the value comes out to be 0.0 it should get updated by the value which i am getting from the snapshot – Jadu Dec 26 '22 at 09:07
  • Firebase calls work asynchronously. So you need to wait until the value is updated in the listener. For now what's happening is the second log is running before updating the user weight value in the listener – Priyanshu Dec 26 '22 at 09:12
  • Can you suggest some changes? – Jadu Dec 26 '22 at 09:13
  • You can checkout the three ways I have suggested – Priyanshu Dec 26 '22 at 09:41

1 Answers1

1

Firebase Calls work asynchronously, so we have different ways to handle it.

1) Callbacks - You can create interface and use callbacks to update the value.

Here is the reference - link

2) Coroutines await() function - You need to add kotlinx-coroutines-play-services library to use await() function. Here is the reference -

import kotlinx.coroutines.tasks.await 
suspend fun getIdTokenForUser (
    user: FirebaseUser
): GetTokenResult {
    return try {
        user.getIdToken().await()
    } 
    catch (e: Exception) {
        // handle error
    }
}

3) Perform action related to user weight inside the listener only

Priyanshu
  • 101
  • 7