I'm working an Android app that has to make server request and then perform actions when the request is completed. Here's some pseudo code to help explain the situation:
makeRequest(new SomeTask{
onDone() {
// Do actionB with queue
}
});
// Do actionA with queue. Must be execute first!!
Here's the implementation of makeRequest
in pseudo code:
makeRequest(SomeTask task) {
if(canDoOptimization) { // if true, don't need to make request
// It's a bad idea to execute this immediately.
// Wish I could wait until the current thread of execution was done...
task.onDone();
return;
}
asyncTask = new AsyncTask<SomeTask, Void, Void>() {
doInBackground(SomeTask... task) {
// Make server request...
task.onDone();
}
}
asyncTask.execute(task);
}
Usually actionA
happens before actionB
as expected, but in cases where we can avoid a network requests, SomeTask.execute
is called immediately. This causes actionB
to occur before actionA
, which is bad. Is there any way I can guarantee this doesn't happen?
I've run into this situation several times in javascript. In those cases, I would wrap the SomeTask.execute
call with a setTimeout
or setImmediate
to maintain the proper async semantics.
For clarity, here's an example of the same bug in JavaScript: https://gist.github.com/xavi-/5882483
Any idea what I should do in Java/Android?