I recently reached a sticking point with the Task interface I had hoped would solve MM’s background task problem. Käppler assumed that users would only need to start a task and pick up results upon completion. His code is very well done and flawlessly executes this behavior. Unfortunately, the very nature of MM is such that the aforementioned behavior is insufficient.
Enter QueryableCallable (and a few choice extra snippets added to Käppler’s Task and TaskInterface)! Now we are able to call a task and post results back to our UI at critical stages of execution. Sample code behind the read more.
Before, what we had was something like:
private QueryableCallablecallableTest = new QueryableCallable (){
int myLocalResult;
public Integer call() throws Exception {
for(int i=0; i<5; i++){
Thread.sleep(1000);
Log.e("Concurrency","Task iterated, i is: " + i);
myLocalResult = i;
}
return myLocalResult;
};
};@Override
public void onTaskFinished(Tasktask) {
if (task.failed()) {
System.err.println("task" + task.getTaskId() + " failed. Reason: "
+ task.getError().getMessage());
} else {
//do some results stuff
}
}
now, what we have is:
private QueryableCallablecallableTest = new QueryableCallable (){
int myLocalResult;
public Integer call() throws Exception {
for(int i=0; i<5; i++){
Thread.sleep(1000);
Log.e("Concurrency","Task iterated, i is: " + i);
myLocalResult = i;
task3.post(ResultView.this, this);
}
return myLocalResult;
};
public Integer postResult() throws Exception {
return myLocalResult;
}
};
@Override
public void onTaskFinished(Tasktask) {
if (task.failed()) {
System.err.println("task" + task.getTaskId() + " failed. Reason: "
+ task.getError().getMessage());
} else {
//do some results stuff
}
}
@Override
public void onTaskPosted(Tasktask) {
if (task.failed()) {
System.err.println("task" + task.getTaskId() + " failed. Reason: "
+ task.getError().getMessage());
} else {
Toast.makeText(this, task.getResult().toString(), Toast.LENGTH_SHORT).show();
}
}