Consolidating responses from N async service calls into 1 response for your client

StackOverflow https://stackoverflow.com/questions/20735722

  •  20-09-2022
  •  | 
  •  

Вопрос

I'm currently doing some Android app development. I'm new to event driven programming. So this is probably a newbie question. Imagine the following logic:

class A {
    function1() {
        call function2(new Callback())
    }

    class Callback implements OnFunction2Done {
        @Override
        onFunction2Done() {

        }
    }
}

class B {
    function2(Callback callback) {
        foreach item 1 - n {
            // call external service which responds via async callback
        }
    }
}

Essentially function1 calls function2 in a different class. As part of the call it also gives a handle to the callback routine to be called once function2 is done doing all it's work. The problem is that function2 itself is making N async service calls. What is the best way to make sure that the callback routine (onFunction2Done()) is called only after all the asynchronous service calls in the for loop (inside function2) have fully completed? It's also OK if in your recommended solution onFunction2Done() does the job of consolidating "n" responses from function2 (one for each time through the loop).

Thanks!

Это было полезно?

Решение

Here's my (perhaps naive) solution, assuming you always get some sort of response (or error callback) from the external service:

class B {
  int counter;
  function2(Callback callback) {
    counter = n;
    foreach item 1 - n {
        //send stuff to external service, service responds in onResponseOrError
    }
   }
 onResponseOrError()  {
   --counter;
   if (counter == 0)
      callback.onFunction2Done();
 }
}

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top