You're firing the onListen(items)
before you've actually checked the existence. Any code that depends on data from the database must be inside the callback that fires when that data is available.
Since you want to perform multiple checks, consider using a counter to check whether all of them completed:
firestoreInstance.collection("users")
.addSnapshotListener { querySnapshot, firebaseFirestoreException ->
if(firebaseFirestoreException !=null){
return@addSnapshotListener
}
val count = 0
val items = mutableListOf<Item>()
querySnapshot?.documents?.forEach {
firestoreInstance.collection("users")
.document(it.id).collection("engagedChatChannels").get()
.continueWith { result->
if(result.result!!.size() > 0)
items.add(
UserItem(
it.toObject(User::class.java)!!,
it.id,
0,
context
)
)
}
count = count + 1
if (count == querySnapshot?.documents?.size) {
onListen(items)
}
}
}
Note that I didn't run the above code, so it may contain syntax errors. However I hope the flow is clear, with both the onListen
call being inside the callback, and the counter used to check if all subcollection checks were done.
The above approach should work, but I'd typically take another approach. If you need to know on a user-level whether they have a certain subcollection, I'd store that fact in a field in each user-document. That way you can simply query the user documents for the ones having the correct value, and prevent this nested loop/query combination.