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
}
null, for a reason unknown to me. What does the documentation of Firebase say aboutnullas token value?