My firebase database looks like this:
Chats
----{userId1}
------{userId2 : true}
------{userId3 : true}
----{userId2}
------{userId1 : true}
------{userId3 : true}
Users
-----{userId1}
---{...}
-----{userId2}
---{...}
-----{userId3}
---{...}
So i want to do basically is list a users chat, for example userId1 who is chatting with userId2 and userId3. This is how im doing it in the ViewModel:
public LiveData<List<Chats>> getChatList() {
DatabaseReference chatsRef = baseRef.child("Chats").child(getCurrentUser);
FirebaseLiveData chatsLivedata = new FirebaseLiveData(chatsRef);
return Transformations.map(chatsLivedata, new Function<DataSnapshot, List<Chats>>() {
@Override
public List<Chats> apply(DataSnapshot dataSnapshot) {
List<Chats> chatsList = new ArrayList<>();
if (dataSnapshot.exists()){
for (DataSnapshot snapshot: dataSnapshot.getChildren()){
usersRef.child(snapshot.getKey()).addValueForSingleEventListener(new ValueEventListener{
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
Chats chat = dataSnapshot.getValue(Chats.class);
chatsList.add(chat);
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
}
}
}
return chatsList;
}
});
}
But the LiveData always return 0 chat item. I understand that its due to the asynchronous nature of firebase, so pls, how else can i implement this? All i want to do is use key under the Chats node to get a node under Users node thanks.