背景
对接设备的时候需要调用厂商提供的SDK,所提供的方法均为异步。
SDK异步方法
同步SDK方法
思路
首先想到的是使用CountDownLatch 等待接口返回结果,但是每调用一个方法都需要这么做的话,冗余代码太多,然后想到的是函数式接口编程BiFunction。
实现
private ScreenResult sendCmdSync(String param, BiFunction<String, ViplexCore.CallBack,Void> function){
final ScreenResult screenResult = new ScreenResult();
CountDownLatch countDownLatch = new CountDownLatch(1);
ViplexCore.CallBack callBack = (int code, String data) -> {
screenResult.setCode(code);
screenResult.setData(data);
countDownLatch.countDown();
};
function.apply(param, callBack);
try {
countDownLatch.await();
} catch (InterruptedException e) {
log.error("{}",e);
}
if(screenResult.getCode() != ErrorTypeEnum.OK.getCode()){
String message = ErrorTypeEnum.getErrorType(screenResult.getCode()).getMessage();
log.error("param:{},code:{},msg:{}",param,screenResult.getCode(),message);
throw new BusinessException(message);
}
return screenResult;
}
Demo
String param = String.format("{\"filePath\":\"%s\"}",path);
ScreenResult screenResult = sendCmdSync(param,(String data, ViplexCore.CallBack callBack) -> {
instance.nvGetXXXXXAsync(data, callBack);
return null;
});
|