1

This function always returns null. t is not being assigned with token value. can someone help pls?

fun getToken(): String? {
    var t: String? = ""
    FirebaseMessaging.getInstance().token.addOnSuccessListener { token: String? ->
        Log.i(TAG,"Token: ${token.toString()}")
        t = token
    }.addOnFailureListener { e: Exception? ->
        Log.e(TAG,"Couldn't get token", e)
    }
    return t
  }
1
  • The only way this function returns null, is when the token value actually IS assigned. It just happens to be null, for a reason unknown to me. What does the documentation of Firebase say about null as token value? Commented Nov 25, 2021 at 11:58

1 Answer 1

2

getToken is returning null because this function completes before the success listener is invoked. getToken doesn't wait for the request to complete. The only thing it does is setting up the success and failure listeners which will be invoked when the request returns a response.

There are a few ways to solve this problem:

  • Mark getToken as suspend and use FirebaseMessaging.getInstance().token.await() to wait until the response is received.
  • Instead of returning the token, you can pass a callback to getToken which will be invoked when the response comes.
    fun getToken(onTokenReceive: (String?) -> Unit) {
        FirebaseMessaging.getInstance().token.addOnSuccessListener { token: String? ->
            Log.i(TAG,"Token: ${token.toString()}")
            onTokenReceive(token)
        }.addOnFailureListener { e: Exception? ->
            Log.e(TAG,"Couldn't get token", e)
            onTokenReceive(null)
        }
    }
    
    So if your were earlier calling the function like this:
    val token = getToken()
    // using the `token` here
    
    Now you can change it to this:
    getToken { token ->
        // use the `token` here
    }
    
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.