Home > OS >  How to map aggregated data from Firestore document back to a Kotlin List
How to map aggregated data from Firestore document back to a Kotlin List

Time:11-07

enter image description hereWould like to reduce the number of reads in my app with Firestore. So I created a document in my collection with the following structure to hold values for 10 "records", that I will get with a single read - since the size of this document is pretty decent, no worries about the 1MB limit size for a single document. I am updating the content of this document with cloud functions.

name of collection: helperz
name of document: top10
field name in top10: tresholdCounter - this I need to check if a single map should be added to top10 or not
field name in top10: top10 . . array of maps


helperz/top10/tresholdCounter
helperz/top10/top10/0/author
helperz/top10/top10/0/name
helperz/top10/top10/0/url
helperz/top10/top10/1/author
helperz/top10/top10/1/name
helperz/top10/top10/1/url
helperz/top10/top10/2/author
helperz/top10/top10/2/name
helperz/top10/top10/2/url
helperz/top10/top10/3/author
helperz/top10/top10/3/name
helperz/top10/top10/3/url
helperz/top10/top10/4/author
helperz/top10/top10/4/name
helperz/top10/top10/4/url
..
helperz/top10/top10/10/author
helperz/top10/top10/10/name
helperz/top10/top10/10/url

I have a data class . . like this:

data class MyClass(
    var name: String? = null,
    var url: String? = null,
    var author: String? = null,
    var counter: Int = 0,
    var free: Boolean? = false,
    var global: Boolean?=true,
    var poses: ArrayList<MyPoze>? = null,
    var docId: string? = null,
    var category: ArrayList<String>? = null,
    @get:PropertyName(CREATED)
    @set:PropertyName(CREATED)
    @ServerTimestamp var created: Timestamp? = null
    )

There are some other fields as well, but for the purpose of this problem, that should be ok.

I have a code for retrieving data from Firestore (in my viewModel):

private fun getHelperzTop10() = viewModelScope.launch {
    Log.d("MP23", "getHelperzTop10")
    val docRef = db.collection("helperz").document("top10")

    docRef.addSnapshotListener { snapshot, e ->
        if (e != null) {
            Log.w("MP23", "Listen failed.", e)
            return@addSnapshotListener
        }

        if (snapshot != null && snapshot.exists()) {
            val docSize = firestoreDocument.getSize(snapshot);
            Log.d("MP23","docSize in Bytes: $docSize, in KB: ${docSize * 0.001}, in MB: ${docSize * 0.000001}"
            )
            val top10 = snapshot.data
            Log.d("MP23", top10!!::class.simpleName.toString() )

            if ("top10" in keys) {
                val top10arr = top10["top10"] as ArrayList<MyClass>
                Log.d("MP23", "we have top10 in top10")
                Log.d("MP23", top10arr!!::class.simpleName.toString())
                Log.d("MP23", top10arr.toString())
            ////            
  • Related