AsyncExecutor

AsyncExecutor is like a thread pool, but with failure (exception) handling. Failures are thrown exceptions and AsyncExecutor will wrap those exceptions inside an event, which is posted automatically.

Disclaimer: AsyncExecutor is a non-core utility class. It might save you some code with error handling in background threads, but it’s not a core EventBus class.

Usually, you call
AsyncExecutor.create() to create an instance and keep it in the Application scope. Then to execute something, implement the
RunnableEx interface and pass it to the execute method of AsyncExecutor. Unlike
Runnable,
RunnableEx may throw an Exception.

If the
RunnableEx implementation throws an exception, it will be catched and wrapped into a ThrowableFailureEvent, which will be posted.

Example for execution:

1

2

3

4

5

6

7

8

9

10

AsyncExecutor.create().execute(

newAsyncExecutor.RunnableEx(){

@Override

publicvoidrun()throwsLoginException{

// No need to catch any Exception (here: LoginException)

remote.login();

EventBus.getDefault().postSticky(newLoggedInEvent());

}

}

);

Example for the receiving part:

1

2

3

4

5

6

7

8

9

@Subscribe(threadMode=ThreadMode.MAIN)

publicvoidhandleLoginEvent(LoggedInEvent event){

// do something

}

@Subscribe(threadMode=ThreadMode.MAIN)

publicvoidhandleFailureEvent(ThrowableFailureEvent event){

// do something

}

AsyncExecutor Builder

If you want to customize your AsyncExecutor instance, call the static method
AsyncExecutor.builder(). It will return a builder which lets you customize the EventBus instance, the thread pool, and the class of the failure event.

Another customization option is the execution scope, which gives failure events context information. For example, a failure event may be relevant only to a specific Activity instance or class.

If your custom failure event class implements the HasExecutionScope interface, AsyncExecutor will set the execution scope automatically. Like this, your subscriber can query the failure event for its execution scope and react depending on it.