0

I'm trying to get a geohash query with coroutines async

override suspend fun getUsersWithGeoHash(
    latitude: Double,
    longitude: Double,
    radiusInMeter: Int
): List<UserEntity> {


    val center = GeoLocation(latitude, longitude)

    val bounds = GeoFireUtils.getGeoHashQueryBounds(center, radiusInMeter.toDouble())

    val tasks : MutableList<Task<QuerySnapshot>> = mutableListOf()

    val boundSize : Int = bounds.size

    var docs = mutableListOf<DocumentSnapshot>()
    var userList = mutableListOf<UserEntity>()

    bounds.forEach {

            geoQueryBounds ->

        val query = fireStore.collection("database/user/userList")
            .orderBy("geohash")
            .startAt(geoQueryBounds.startHash)
            .endAt(geoQueryBounds.endHash)

        tasks.add(query.get())
    }

    Log.d("user-get", "before->"+ tasks.size)

    Log.d("user-get", "before->"+ docs.size)




    var deferred : Deferred<Task<List<Task<*>>>> = CoroutineScope(Dispatchers.IO).async {


        Tasks.whenAllComplete(tasks)
            .addOnCompleteListener {

                Log.d("user-get", "on-0-> addOnComplete")

                tasks.forEach { task ->

                    val snapshot = task.result

                    Log.d("user-get", "on->"+ task.toString())

                    snapshot.documents.forEach {

                        docs.add(it)

                    }


                }
            }


    }

    Log.d("user-get", "after ->"+ docs.size)



    val result = deferred.await()
    Log.d("user-get", "result -> "+ result.toString())

    Log.d("user-get", "after ->"+ docs.size)




    docs.forEach {
                documentSnapshot ->

            val user = documentSnapshot.toObject(UserEntity::class.java)

            if (user != null) {
                userList.add(user)
            }
        }





    return userList
}

this is code I created. but 'userList' has no any user ...

enter image description here

I expected this log.d order

before - > 3

before - > 0

on-0-> addOnComplete

on->com.google.android.gms.tasks.zzw@539056a

on->com.google.android.gms.tasks.zzw@2e9ca5b

on->com.google.android.gms.tasks.zzw@69512f8

after ->0

result -> com.google.android.gms.tasks.zzw@a0897cc

after ->0

user-getwithhash: size -> 0 (this is at viewmodel)

how can I implement that function like above??

tring yuo
  • 67
  • 6
  • What exactly in this code doesn't work the way you expect? Tell us what is wrong with shared code. Do you have any errors? – Alex Mamo Sep 07 '22 at 06:28
  • I thought Tasks.whenAllComplete completed and docs.forEach loop started. because of await ... but that deferred and await not working – tring yuo Sep 07 '22 at 06:48
  • Have you tried to get `Tasks.whenAllComplete(tasks)` outside the `CoroutineScope(Dispatchers.IO)`? as the operation is already executing in another thread, right? Please respond using @AlexMamo – Alex Mamo Sep 07 '22 at 10:41

0 Answers0