Prateek Ratnaker
Prateek Ratnaker

Reputation: 817

Android Volley request synchronisation issue

I have a handler which runs inside a service. Inside the handler, I run two for loops.

In first for loop, I fetch some data from the database and make volley requests per iterations. The response from these volley requests make changes to some files stored in filesystem and some database changes. The second for loop needs to work on changes made by these requests in the first loop. For this purpose, the second for loop needs to wait for changes made requests I the first loop. However, the requests in the first loop need more time to be completed. The second for loop runs before these changes are made and hence no new request are made by second for loop since no data changes are received.

How to wait the second for loop until all requests from first for loop is completed?

private final class Handler extends Handler {
  public Handler(Looper looper) {
    super(looper);
  }

  @Override
  public void handleMessage(Message msg) {
        //1st for loop
    for (do some database processing) {
      volleyrequestclass.make a volley request....the response from this volleyrequest make certain changes to database and filesystem
    }

    //2nd for loop ...this needs to wait till all requests from loop1 are successfully completed
    for(process on changes made by request in loop1)
    {
    make a volley request based on changes made by requests in first loop
    }
  }
}

Upvotes: 0

Views: 140

Answers (1)

Damanpreet Singh
Damanpreet Singh

Reputation: 726

One solution would be to use RequesFuture

//1st for loop 
for (do some database processing) {

  RequestFuture<String> future = RequestFuture.newFuture(); 
  StringRequest stringRequest = new StringRequest(Request.Method.GET, url, future, future);
  RestPlatform.getInstance(Application.instance).getRequestQueue().add(stringRequest);
 future.get();
}

This solution would stop you from hitting parallel requests. Another solution can be :

//n is number of times loop will be running. 
final CountDownLatch signal = new CountDownLatch(n);
//Volley Request
//In listener or onResponse do 
signal.countdown();

   //1st for loop 
for (do some database processing) {
  volleyrequestclass.make a volley request....the response from this volleyrequest make certain changes to database and filesystem 
} 
 // here you need to await untill your countdown is not zero. 
try {
  signal.await();// wait for callback
} catch (InterruptedException e) {
  throwTestEvironmentException(e);
}
//2nd for loop ...this needs to wait till all requests from loop1 are successfully completed 
for(process on changes made by request in loop1) 
{ 
make a volley request based on changes made by requests in first loop 
} 

So these are the two solutions that can work efficiently.

Upvotes: 1

Related Questions