1

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 Answer 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();
}
Sign up to request clarification or add additional context in comments.

1 Comment

Works perfectly. My solution had many more lines of code involving Thread.join() etc. And it didn't work -- this is so much nicer!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.