How to merge results of two queries in Firebase Realtime Database

Issue

I want to take the data of the child called news to a list. Can I get the department key only when all or Management?

Here is my code:

query = MainNewsDb.orderByChild("department").equalTo("Management").limitToLast((int)limit);
query.addValueEventListener(valueEventListener1);

query1 = NewsListDb1.orderByChild("department").equalTo("all").limitToLast((int)limit);
query1.addValueEventListener(valueEventListener1);

This Is My RTDB:

enter image description here

Solution

To get the combined result of two separate Firebase Realtime Database queries, I recommend you to use Tasks.whenAllSuccess() method. You can achieve this, using the following lines of code:

query = MainNewsDb.orderByChild("department").equalTo("Management").limitToLast((int)limit);
query1 = NewsListDb1.orderByChild("department").equalTo("all").limitToLast((int)limit);

Task firstTask = query.get();
Task secondTask = query1.get();

Task combinedTask = Tasks.whenAllSuccess(firstTask, secondTask).addOnSuccessListener(new OnSuccessListener<List<Object>>() {
    @Override
    public void onSuccess(List<Object> list) {
         //Do what you need to do with your list
    }
});

As you can see, when overriding the "onSuccess()" method the result is a list of objects. As soon as you have it, simply map each object from the list into an object of the desired type.

Answered By – Alex Mamo

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published