AsyncExecutor
AsyncExecutor类似于线程池,但具有失败(异常)处理。失败是抛出异常,AsyncExecutor将把这些异常封装在一个事件中,该事件将自动发布。
免责声明:AsyncExecutor是一个非核心实用程序类。它可能会在后台线程中为您节省一些错误处理代码,但它不是一个核心EventBus类。
通常,您调用 AsyncExecutor.create() 来创建一个实例并将其保存在应用程序范围内。然后要执行某些操作,请实现 RunnableEx接口并将其传递给AsyncExecutor的execute方法。与Runnable不同,RunnableEx可能抛出异常。
如果RunnableEx实现抛出异常,它将被捕获并封装到 ThrowableFailureEvent 中,该事件将被发布。
执行示例:
AsyncExecutor.create().execute(
new AsyncExecutor.RunnableEx() {
@Override
public void run() throws LoginException {
// No need to catch any Exception (here: LoginException)
remote.login();
EventBus.getDefault().postSticky(new LoggedInEvent());
}
}
);
接收示例:
@Subscribe(threadMode = ThreadMode.MAIN)
public void handleLoginEvent(LoggedInEvent event) {
// do something
}
@Subscribe(threadMode = ThreadMode.MAIN)
public void handleFailureEvent(ThrowableFailureEvent event) {
// do something
}
AsyncExecutor Builder
如果希望自定义AsyncExecutor实例,请调用静态方法AsyncExecutor.builder()。它将返回一个建造者(builder),它允许您定制EventBus实例、线程池和失败事件类(customize the EventBus instance, the thread pool, and the class of the failure event.)。
另一个定制选项是执行范围,它提供失败事件上下文信息(execution scope, which gives failure events context information)。例如,失败事件可能只与特定的Activity实例或类相关。
如果您的自定义故障事件类实现了 HasExecutionScope 接口,AsyncExecutor将自动设置执行范围。这样,您的订阅者就可以查询失败事件的执行范围,并根据它做出反应。
由于作者水平有限,语言描述及代码实现中难免有纰漏,望各位看官多提宝贵意见!
Hello , World !
感谢所有!