2

I'd like to read from several Firebase nodes before performing some actions with the retrieved data. Currently, I have accomplished this by nesting each request in the completion listener of previous request, but nesting makes code hard to maintain. Is there a way to perform several requests in succession or simultaneously and listen when all of them are complete?

AL.
  • 36,815
  • 10
  • 142
  • 281
wilkas
  • 1,161
  • 1
  • 12
  • 34

1 Answers1

3

Example if you have two request and you want to run some code after both of them completed and/or succeed:

Boolean ref1done = false;
Boolean ref2done = false;

// if you need data from snapshot
DataSnapshot result1;
DataSnapshot result2;

ref1done = false;
dataRef1.addValueEventListener(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        ref1done = true;
        result1 = dataSnapshot;
        doThisAfter();
    }
    ...
});

ref2done = false;
dataRef2.addValueEventListener(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        ref2done = true;
        result2 = dataSnapshot;
        doThisAfter();
    }
    ...
});

...

public function doThisAfter() {
    if (ref1done && ref2done) {
        // do something
        // if you need data from snapshot, it can be accessed from result1 and result2
    }
}

This might be not the best solution, I'm also still searching if there is a better one. Or maybe you can try using EventBus.

koceeng
  • 2,169
  • 3
  • 16
  • 37
  • 1
    Well thats one way of doing it and quite simple, though I wonder if there would be any performance reduction for 4 requests done like that. I was thinking of creating ArrayList of ValueEventListeners, pass them to the object, which would run them one by one, use custom event listener which would fire upon completion of one ValueEventListener to process the second and when all are processed fire up total completion event and return ArrayList of datasnapshots :) – wilkas Feb 21 '17 at 07:54
  • 1
    I'l accept answer tomorrow if no better solutions will be given. – wilkas Feb 21 '17 at 07:55
  • 1
    Currently I'm using 5-6 request at the same time when app start. I've noticed no significant difference than when I only call 1 request. But I'm also still learning though. You might want to see [this page that I just found](http://stackoverflow.com/questions/35931526/) – koceeng Feb 21 '17 at 08:26