Reputation: 33
I wrote method that contains two async methods that create connection with firebase. I want to finish the method after all the async methods finish. How can i do this? If it was one async method so i was create callBack interface but is not helpful in this situation.
For example:
public void method(String teamID1,String teamID2)
{
final ArrayList<String> usersID = new ArrayList<>();
final DatabaseReference mDatabase1 = getDatabaseReference(ConstantNames.ROLE_PATH).child ( teamID1 );
mDatabase1.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot snapshot) {
usersID.add(snapshot.getValue().toString());
}
@Override
public void onCancelled(@NonNull DatabaseError error) {
}
});
final DatabaseReference mDatabase2 = getDatabaseReference(ConstantNames.ROLE_PATH).child ( 2 );
mDatabase2.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot snapshot) {
usersID.add(snapshot.getValue().toString());
}
@Override
public void onCancelled(@NonNull DatabaseError error) {
}
});
}
(This method is just for illustration)
I want finish this method when listener of mDatabase1 and listener of mDatabase2 called. How can i do it?
Upvotes: 1
Views: 553
Reputation: 598728
I recommend using the brand new get()
method for this. This method does almost the same as addListenerForSingleValueEvent
, but:
Task<DataSnapshot>
.That last bit is relevant for you, as it allows you to then use Tasks.whenAll()
on the tasks for your two database calls here.
Also see:
get()
API vs the addListenerForSingleValueEvent
APITasks.whenAll
.Tasks.whenAll()
.Upvotes: 1