https://kotlinlang.org logo
Title
j

james

02/08/2021, 12:02 PM
I wasn't sure wether to post here or in #android, but the issue I'm having is with the Kotlin coroutines library. Just need some help getting my head around what I'm doing wrong!
# MainActivity.kt

override fun onStart() {
        super.onStart()
        var applicationID = runBlocking { Application.registerDevice() }

        Log.d("AppID on-start", applicationID)
    }
# Application.kt

object Application {
    suspend fun registerDevice(): String {
        return getTokenAsync().await()
    }

    private suspend fun getTokenAsync(): kotlinx.coroutines.Deferred<String> = coroutineScope {
        async {
            return@async FirebaseInstallations.getInstance().id.result.toString()
        }
    }
}
E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.application, PID: 20890
    java.lang.IllegalStateException: Task is not yet complete
If anyone could see where I'm going wrong and help point me in the right direction on what I can do to resolve this I would really appreciate it 🙂 Thanks in advance!
a

Ali Albaali

02/08/2021, 2:06 PM
Have you tried removing the `return`s?
j

james

02/08/2021, 2:09 PM
I still get Task is not yet completed with the returns removed
a

Ali Albaali

02/08/2021, 2:15 PM
Firebase is already asynchronous so wrapping it with Coroutines won't help.
j

james

02/08/2021, 2:18 PM
I’ve also tried running it in a function like this
private fun fetchID(): String {
        var token: String
        FirebaseInstallations.getInstance().id
            .addOnCompleteListener(OnCompleteListener<String?> { task ->
                if (task.isSuccessful) {
                    token = task.result.toString()
                    Log.d("App-Token", token)
                }
            })
        return token
    }
But token is not initialised and if I initialise it then it won’t use the updated value from the Firebase function
a

Ali Albaali

02/08/2021, 2:20 PM
You're saying it will return immediately, correct?
j

james

02/08/2021, 2:23 PM
I guess so? This is how it’s being called
fun registerDevice() {
        val token = fetchID()
        // do other stuff with token
    }
How would I go about waiting for it to return the FirebaseInstallations task?
You can see the example in there about how you would set up a callback with your onCompletion listener
j

james

02/09/2021, 1:36 PM
Perfect got it sorted, thank you @akatkov :)
👍 1