Home > front end >  Value is not assigned In Successlistener Android
Value is not assigned In Successlistener Android

Time:12-26

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

CodePudding user response:

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

  • Related