Search code examples
javaandroidasynchronousandroid-volleysequential

Android - Asynchronous Network Calls - Response dependent on each other


I just encountered this sort of a situation while developing an Android application today where I was required to render graphs based on responses from 2 different API's. I'm using Volley and what I did is I made a sequential network call i.e I made the 1st request, and in the onResponse method of that request I made the 2nd request. And then I render the view (the graph) in the onResponse method of 2nd request.

Now I want to optimize this situation. I want to know a way I can make these 2 network calls asynchronously where I render the view only after receiving responses from both API's. So, say I have 3 modular methods namely -

  1. getDataFromServer1 (network call to get data from one server)
  2. getDataFromServer2 (network call to get data from another server)
  3. loadView (render graphs based on data received from 2 network calls)

How do I go about it ? Can someone throw some light upon it ?


Solution

  • @tommus solution is the best approach.


    If you want to go with simple or less code approach, You can use a boolean flag to ensure that both are executed and move forward based on condition.

    Declare a volatile boolean variable that will be used as a flag.

    private volatile boolean flag = false;
    

    flag would be false at start. Now, make call to both webservices. Any service that is executed will turn this flag TRUE.

    getDataFromServer1();
    function void onCompleteServer1() {
        if(flag) {
           loadViews();
        } else {
           flag = true;
        }
    }
    
    
    getDataFromServer2();
    onCompleteServer2Request() {
        if(flag) {
           loadViews();
        } else {
           flag = true;
        }
    }