您可以将lambda用作回调,以便在检索数据时收到通知,例如:
fun loadList(callback: (list: List<MyClass>) -> Unit) {
myRef.addListenerForSingleValueEvent(object : ValueEventListener {
override fun onCancelled(snapshotError: DatabaseError) {
TODO("not implemented")
}
override fun onDataChange(snapshot: DataSnapshot) {
val list : MutableList<MyClass> = mutableListOf()
val children = snapshot!!.children
children.forEach {
list.add(it.getValue(MyClass::class.java))
}
callback(list)
}
})
}
调用该函数时,可以在末尾指定加载列表时要通知的lambda:
loadList {
// `it` contains the list
}