I wasn't sure wether to post here or in <#C0B8M7BU...
# coroutines
j
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!
Copy code
# MainActivity.kt

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

        Log.d("AppID on-start", applicationID)
    }
Copy code
# 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()
        }
    }
}
Copy code
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
Have you tried removing the `return`s?
j
I still get Task is not yet completed with the returns removed
a
Firebase is already asynchronous so wrapping it with Coroutines won't help.
j
I’ve also tried running it in a function like this
Copy code
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
You're saying it will return immediately, correct?
j
I guess so? This is how it’s being called
Copy code
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
Perfect got it sorted, thank you @akatkov :)
👍 1