Firebase和检索元素

我正在尝试从Firebase中读取x个元素,但是我有一种感觉,我误解了一些东西。

DataSnapshot返回正确的子数,但是当我试图循环通过子,循环从不执行。

注意:代码在Kotlin

fun list(count: Int, callback: ListCallback) { val playersRef = firebase.child("players") val queryRef = playersRef.orderByChild("rank").limitToFirst(count) queryRef.addListenerForSingleValueEvent(object : ValueEventListener { override fun onCancelled(error: FirebaseError?) { Log.e("firebase", error!!.message) } override fun onDataChange(snapshot: DataSnapshot?) { val children = snapshot!!.children // This returns the correct child count... Log.i("firebase", children.count().toString()) val list = ArrayList<Entry>() // However, this loop never executes children.forEach { val e = Entry() e.name = it.child("name").value as String e.rank = it.child("rank").value as Long e.wins = it.child("wins").value as Long e.losses = it.child("losses").value as Long Log.i("firebase", e.toString()) list.add(e) } callback.onList(list) } }) } 

这适用于我:

 val firebase: Firebase = Firebase("https://stackoverflow.firebaseio.com/34378547") fun main(args: Array<String>) { list(3) Thread.sleep(5000) } fun list(count: Int) { val playersRef = firebase.child("players") val queryRef = playersRef.orderByChild("rank").limitToFirst(count) queryRef.addListenerForSingleValueEvent(object : ValueEventListener { override fun onCancelled(error: FirebaseError?) { println(error!!.message) } override fun onDataChange(snapshot: DataSnapshot?) { val children = snapshot!!.children // This returns the correct child count... println("count: "+snapshot.children.count().toString()) children.forEach { println(it.toString()) } } }) } 

输出:

 count: 2 DataSnapshot { key = -K6-Zs5P1FJLk4zSgNZn, value = {wins=13, name=fluxi, rank=1, losses=1} } DataSnapshot { key = -K6-ZtdotHkkBzs5on9X, value = {wins=10, name=puf, rank=2, losses=42} } 

更新

在评论中有一些关于为什么snapshot.children.count()工作,而children.count()不工作的讨论。 问题是由两个事实引起的:

  1. Firebase的DataSnapshot.getChildren()返回一个Iterable ,它只能被迭代(就像Iterable的契约一样)。
  2. Kotlin count()遍历Iterable来计算其项目。

所以在Kotlin的count()完成之后, Iterable就在序列的末尾。 随后for循环没有什么可以循环了。 在我的片段中,我分别调用snapshot.children来获得一个单独的迭代器来获取计数。

了解Kotlin如何实现count() ,最好使用Firebase的内置childrenCount

 println("count: "+snapshot.childrenCount)