Java – Android – asynchronous network call – response interdependence

I encountered this situation when developing Android applications today. I need to render graphics according to the responses from two different APIs I'm using volley. What I do is I make a sequential network call, that is, I make the first request, and I make the second request in the onresponse method of the request Then I render the view (graph) in the onresponse method of the second request

Now I want to optimize this situation I want to know a way that I can make these two network calls asynchronously. I only render the view after receiving the responses from the two APIs So I say there are three modular methods, namely –

>Getdatafromserver1 (network call to get data from one server) > getdatafromserver2 (network call to get data from another server) > loadview (render chart based on data received from 2 network calls)

What should I do? Can anyone scoff at it?

Solution

@Tommus solution is the best method

If you want to use simple or less code methods, you can use Boolean flags to ensure that both are executed and move forward according to conditions

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

private volatile boolean flag = false;

The flag will be false at the beginning Now, call two WebServices Any service executed will set this flag to true

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


getDataFromServer2();
onCompleteServer2Request() {
    if(flag) {
       loadViews();
    } else {
       flag = true;
    }
}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>