Java同步函数来自带回调的异步函数
我有一个如下所示的同步函数:Java同步函数来自带回调的异步函数,java,asynchronous,Java,Asynchronous,我有一个如下所示的同步函数: void doStuff(int x, String y, Consumer<String> onSuccess, Consumer<Throwable> onFail) { // start something that happens on other Threads using RxJava that eventually either // 1) Calls onSuccess(String) or onFail(Thro
void doStuff(int x, String y, Consumer<String> onSuccess, Consumer<Throwable> onFail) {
// start something that happens on other Threads using RxJava that eventually either
// 1) Calls onSuccess(String) or onFail(Throwable)
// 2) returns to caller right away after starting this mess off
}
Result doStuffSync(整数x,字符串y){
BlockingQueue结果=新的ArrayBlockingQueue(1);
多斯塔夫(
x、 y,,
(s) ->result.add(一个或多个的结果),
(x) ->result.add(result.failure(x));
返回结果。take();
}
工作得很好。我的解决方案有更多的代码行,涉及Thread.join()
等,但它没有工作——这太好了!
Result doStuffSync(int x, String y) {
// magic that calls `doStuff` with callbacks that enable the entire thing to run
// within this function and build a Result
return result;
}
Result doStuffSync(int x, String y) {
BlockingQueue<Result> result = new ArrayBlockingQueue<>(1);
doStuff(
x, y,
(s) -> result.add(Result.of(s)),
(x) -> result.add(Result.failure(x));
return result.take();
}