Android Firestore Query in Kotlin Coroutines (Async without Callback)

July 23, 2019

Dependencies

dependencies {
    // https://mvnrepository.com/artifact/org.jetbrains.kotlinx/kotlinx-coroutines-android
    implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.2.1'
    // https://mvnrepository.com/artifact/org.jetbrains.kotlinx/kotlinx-coroutines-play-services
    implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-play-services:1.2.1'
}

Usage

launch(Dispatchers.Default) {
    val item = firestore.collection("COLLECTION").document("DOCUMENT_ID").get().await()
}

or

launch(Dispatchers.Default) {
    val d1 = firestore.collection("COLLECTION").document("DOCUMENT_ID").get().asDeferred()
    val d2 = firestore.collection("COLLECTION2").document("DOCUMENT_ID2").get().asDeferred()

    val (item1, item2) = listOf(d1, d2).awaitAll()
}
This work is licensed under a
Creative Commons Attribution-NonCommercial 4.0 International License.