Analysis of Andorid jar Library Source Code Bolts Principle

  • 2021-12-04 11:11:27
  • OfStack

Bolts:
Function:
Used to chain cross-thread code and pass data

Chestnuts:
Copy code
Task.call(new Callable < Boolean > () {
@Override
public Boolean call() throws Exception {
return true;
}
}, Task.UI_THREAD_EXECUTOR);

Task.callInBackground(new Callable < Boolean > () {
@Override
public Boolean call() throws Exception {
return false;
}
});

Task.callInBackground(new Callable < Boolean > () {
@Override
public Boolean call() throws Exception {
return true;
}
}).onSuccess(new Continuation < Boolean, Object > () {
@Override
public Object then(Task < Boolean > task) throws Exception {
if (task.getResult()) {
return null;
} else {
return new Object();
}
}
}, Task.BACKGROUND_EXECUTOR).continueWith(new Continuation < Object, Object > () {
@Override
public Object then(Task < Object > task) throws Exception {
if (task.getResult() == null) {
Toast.makeText(getBaseContext(), "null", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getBaseContext(), "not null", Toast.LENGTH_SHORT).show();
}

return null;
}
}, Task.UI_THREAD_EXECUTOR);
Copy code
Source code interpretation:
Internally by maintaining multiple ExecutorService objects and by concatenating the call.

And by maintaining the internal variable at the specified process, that is, the specific value, the value is obtained through the object getResult of Task.

UIThread

Copy code
/**
* An {@link java.util.concurrent.Executor} that runs tasks on the UI thread.
*/
private static class UIThreadExecutor implements Executor {
@Override
public void execute(Runnable command) {
new Handler(Looper.getMainLooper()).post(command);
}
}
Copy code
BackgroundThread


Related articles: