nuebKitsune nuebKitsune - 6 months ago 14
Java Question

Java Async Invoke in method Waiting on Return

I know there are probably a couple ways to do this, just looking for the most efficient and concise way to go about it:

public Object giveMeNewObject() {
final Object result = null;
SomeApiClient.start(new Callback() { // starts an async process
@Override
public void onSuccess(Object somethingNew) {
result = somethingNew; //ERROR; can't set cause final
}
});
return result; //result is null, cause Async already finished
}

Answer

From your code - this is modified on fly so correct mistakes and all will work as you expect - caller will wait untill 3rd party finishes the processing and will get the result of that process:

public Object giveMeNewObject() {
    CountDownLatch latch=new CountDownLatch(1);
    Callback callback=new Callback() { 
      public sometype result=null;
        @Override
        public void onSuccess(Object somethingNew) {
            result = somethingNew; //ERROR; can't set cause final
            latch.countDown();
        }
    });
    SomeApiClient.start(callback);
    latch.await(sometimetowait);
    return callback.result;

}