英文:
Java synchronous function from async function with callbacks
问题
我有一个看起来像这样的同步函数:
void doStuff(int x, String y, Consumer<String> onSuccess, Consumer<Throwable> onFail) {
// 在其他线程上启动一些使用 RxJava 执行的操作,最终要么
// 1)调用 onSuccess(String) 或 onFail(Throwable)
// 2)在启动这一混乱过程后立即返回给调用者
}
我想写一个包装器,使其同步调用。我已经编写了一个名为 Result
的类,用于返回给调用者。它将包含一个 String
或一个 Throwable
。我正在尝试解决的问题是如何调用异步函数并使用其 onSuccess
和 onFail
参数来发出信号,使 doStuff
函数应该退出并返回正确的 Result
。
Result doStuffSync(int x, String y) {
// 执行一些魔法,使用能够在此函数内运行整个过程的回调来调用 `doStuff`,并构建一个 Result
return result;
}
英文:
I have a synchronous function that looks like this:
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
}
I want to write a wrapper around this that calls it synchronously. I've already written a class named Result
to return to the caller. It will either have a String
or a Throwable
in it. What I'm trying to do is figure out how call the async function and use its onSuccess
and onFail
parameters to signal that the doStuff
function should exit returning the proper Result
.
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;
}
答案1
得分: 2
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();
}
英文:
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();
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论