Reputation: 12826
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;
}
Upvotes: 1
Views: 214
Reputation: 198033
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();
}
Upvotes: 2