【发布时间】:2020-05-19 08:42:41
【问题描述】:
在我的项目中,我根据 List 的大小在 for 循环中调用 Firebase 数据库 n 次,并通过获取每个侦听器的响应来返回结果。我在 Coroutine 中完成所有这些工作。这是我的代码
fun Flow<List<Basket>>.mapBasketListToItemsList() : Flow<List<Items>> = map{it : List<Basket> ->
val itemsList = Collections.synchronizedList(ArrayList<Items>())
coroutineScope{
it.forEach {it : Basket ->
launch {
databaseReference.child("Items").child(it.itemsId!!)
.addListenerForSingleValueEvent(object : ValueEventListener {
override fun onCancelled(p0: DatabaseError) {
}
override fun onDataChange(dataSnapshot: DataSnapshot) {
if (dataSnapshot.exists()) {
val item = dataSnapshot.getValue(Items::class.java)
itemsList.add(item!!)
}
}
})
}
}
}
itemsList
}
但我感觉很奇怪,因为我不知道我这样做是否正确。所以我想知道是否有更好的方法来完成这项工作。
【问题讨论】:
-
您好 Mattwalk,欢迎来到 SO。你有没有看过协程和延续?这是一个提到 Firebase 的问题,也许它会给你一个指向那个方向的指针? (它仍然是 PITA,顺便说一句)github.com/Kotlin/kotlinx.coroutines/issues/48
-
好的,我看看
-
@AnoopM 好吧...
标签: android multithreading firebase kotlin coroutine