How can I await (or run infinitely a function in o...
# coroutines
p
How can I await (or run infinitely a function in order to listen to keep listening to events). I know this might sound a bit odd, but I'm not really doing actual tests for my codebase, but rather trying to learn more about Firebase's SDK (which is apparently only accessible through Android), and hence I found that running Unit tests on the JVM is the best way to deal to go about this (without having to deal with an emulator/physical device overhead)
Copy code
@Test
fun retrieveData() = runTest(timeout = Duration.INFINITE) {
    Firebase.firestore
        .collection("gaming").document("gaming")
        .get()
        .addOnFailureListener {
            println("Failure")
        }
        .addOnSuccessListener {
            println(it.data)
        }
        .addOnCompleteListener {
            println("Done")
        }
        .await()
        .let {
            println(it.data) // Only this line prints
        }
}
🧵 2
l
You can wrap subscriptions using Flow, have a look at the
callbackFlow
builder
p
@Leon Kiefer I've tried to convert the callback to a suspend function
Copy code
suspend fun getDocument() = suspendCoroutine { continuation ->
    Firebase.firestore
        .collection("gaming")
        .document("gaming")
        .get()
        .addOnCompleteListener {
            continuation.resume(true)
        }
        .addOnFailureListener { exception ->
            continuation.resume(null)
        }
        .addOnSuccessListener { result ->
            continuation.resume(result)
        }
     }
but it never returns
👎🏼 1
l
You can call getDocument with a timeout using
withTimeout
, also you should pass the exception of the callback to the continuation
For the Firebase SDK there are also kotlin extensions for coroutines already I think, so you don't need write them yourself
p
> call getDocument with a timeout I was just curious why it doesn't invoke any of the callbacks in any of those cases > kotlin extensions for coroutines Ya. I was just reading about it in terms how things evolved from java callbacks, and that behavior piqued my interest
l
Firebase already has Flow extensions with the KTX artifact. Those have been reviewed by the community to be correct. BTW, never use
suspendCoroutine
, it can lead to memory leaks because it can prevent cancellation from happening. Use
suspendCancellabeCoroutine
instead.