Java中从异步函数到同步函数的转换,使用回调函数。

huangapple go评论79阅读模式
英文:

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。我正在尝试解决的问题是如何调用异步函数并使用其 onSuccessonFail 参数来发出信号,使 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&lt;String&gt; onSuccess, Consumer&lt;Throwable&gt; 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&lt;Result&gt; result = new ArrayBlockingQueue&lt;&gt;(1);
  doStuff(
    x, y,
    (s) -&gt; result.add(Result.of(s)),
    (x) -&gt; result.add(Result.failure(x));
  return result.take();
}

huangapple
  • 本文由 发表于 2020年10月1日 02:49:20
  • 转载请务必保留本文链接:https://go.coder-hub.com/64143959.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定