There is no way to wait for all data to be loaded without blocking the user from using your app. That's why the rule of thumb is always the same: any code that needs the data from the database needs to be inside the addOnCompleteListener
callback, or be called from there.
The idiomatic way is to not wait for the data to be loaded, but instead tell the adapter about the new data as it comes in. You can do that by calling notifyDataSetChanged
inside your addOnCompleteListener
:
db
.child("groups/$groupID")
.addValueEventListener(object : ValueEventListener {
override fun onDataChange(snapshot: DataSnapshot) {
db
.child("users")
.child(friendID)
.get()
.addOnCompleteListener { task ->
// check for something
// add to groups list if data is OK
groupsAdapter.notifyDataSetChanged()
}
}
In cases where you really must run some code after all data has loaded, a common approach is to keep a counter of the number of friends you've already loaded, and check against that inside the addOnCompleteListener
.
So something like:
.addOnCompleteListener { task ->
// check for something
// add to groups list if data is OK
if (friendsLoadedCount++ === groupsObject.keys.size()) {
// TODO: all friends have loaded, so do something with them
}
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…