I was trying to fetch an arraylist from Firestore using coroutine kotlin. I wrote two different methods to get same result. These are the methods
MethodA
fun methodA(type: String) {
CoroutineScope(IO).launch {
val myList = mutableListOf<Product>()
val job = async(IO) {
db.collection("Products").get().addOnSuccessListener { snapShot ->
snapShot.forEach { subSnapShot ->
if (subSnapShot.exists()) {
if (subSnapShot["name"]?.equals(type) == true) {
val category = type
val url = subSnapShot["url"].toString()
val type = subSnapShot["type"].toString()
val item = Product(url, category, subSnapShot.id, type)
myList.add(item)
}
}
}
}
myList
}.await()
temp.postValue(job)
}
}
MethodB
fun methodB(type: String) {
CoroutineScope(IO).launch {
val myList = mutableListOf<Product>()
db.collection("Products").get().addOnSuccessListener { snapShot ->
snapShot.forEach { subSnapShot ->
if (subSnapShot.exists()) {
if (subSnapShot["name"]?.equals(type) == true) {
val category = type
val url = subSnapShot["url"].toString()
val type = subSnapShot["type"].toString()
val item = Product(url, category, subSnapShot.id, type)
myList.add(item)
}
}
}
}.await()
temp.postValue(myList)
}
}
I was expecting to get same result from these two methods but MethodA returns an empty list while MethodB returns list of item. How do i fix my MethodA if i fetch list like this unlike MethodB