【问题标题】:Java synchronous function from async function with callbacks来自带有回调的异步函数的 Java 同步函数
【发布时间】:2020-09-30 18:49:20
【问题描述】:

我有一个如下所示的同步函数:

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 的类来返回给调用者。它将有一个String 或一个Throwable。我要做的是弄清楚如何调用异步函数并使用它的onSuccessonFail 参数来表示doStuff 函数应该退出返回正确的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;
}

【问题讨论】:

    标签: java asynchronous


    【解决方案1】:
    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();
    }
    

    【讨论】:

    • 完美运行。我的解决方案有更多涉及Thread.join() 等的代码行。但它没有用——这好多了!
    猜你喜欢
    • 1970-01-01
    • 2012-07-25
    • 2020-04-20
    • 1970-01-01
    • 1970-01-01
    • 2013-07-12
    • 2021-02-20
    • 2021-02-23
    • 2015-03-19
    相关资源
    最近更新 更多