1、概述
StepListener提供了一种包含了多个异步操作的工作流方式。
2、StepListener类
2.1 类结构
StepListener:是NotifyOnceListener抽象类的实现类,其实现了抽象类方法中的innerOnResponse, innerOnFailure,两个实现都是调用代理类ListenableFuture的方法,其中delegate是被代理对象,实现处理响应与异常。
NotifyOnceListener:对于响应及异常只触发一次的ActionListener的实现类。
2.2 方法
2.2.1 whenComplete
向delegate添加监听器。
public void whenComplete(CheckedConsumer<Response, Exception> onResponse, Consumer<Exception> onFailure) {
addListener(ActionListener.wrap(onResponse, onFailure));
}
public void addListener(ActionListener<Response> listener) {
delegate.addListener(listener, EsExecutors.newDirectExecutorService());
}
2.2.2 thenCombine
合并StepListener,等待两个都完成,合并结果。
public <OtherResponse, OuterResponse> StepListener<OuterResponse> thenCombine(
StepListener<OtherResponse> other,
BiFunction<Response, OtherResponse, OuterResponse> fn) {
final StepListener<OuterResponse> combined = new StepListener<>();
whenComplete(r1 -> other.whenComplete(r2 -> combined.onResponse(fn.apply(r1, r2)), combined::onFailure), combined::onFailure);
return combined;
}
3、ListenableFuture
继承BaseFuture实现ActionListener,在处理完后,会遍历执行listeners。