Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to wait for callback before leaving method (Java)

Tags:

java

android

I have a method in which I call another method that has a callback. I want to receive this callback before leaving my method. I saw some other posts in which latches are used. My code looks like this:

public  void requestSecurityToken(<some params>){
    final CountDownLatch latch = new CountDownLatch(1);
    MyFunction.execute(<someParams>, new RequestListener<Login>() {
        @Override
        public void onRequestFailure(SpiceException spiceException) {
            //TODO
        }

        @Override
        public void onRequestSuccess(Login login) {
            //handle some other stuff
            latch.countDown();

        }
    });


    try {
        latch.await();
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
}

This doesn't work, the method is stuck in the await() function. What happens is that, the method immediately jumps to the await(), and doesn't go into the onRequestSuccess() or onRequestFailure() method again. I guess this is a concurency problem... Any ideas on how to fix this issue?

EDIT: Added the line of code where I create the latch.

like image 632
Michiel Willocx Avatar asked Mar 04 '26 02:03

Michiel Willocx


1 Answers

When you are doing this

new RequestListener<Login>

You are passing an object to your function , which implements an interface.
That is why those methods are not getting called , those methods are called only when you get the request result (success or failure).
You can do this instead.

MyFunction.execute(<someParams>, new RequestListener<Login>() {
    @Override
    public void onRequestFailure(SpiceException spiceException) {
        someFunction();
    }

    @Override
    public void onRequestSuccess(Login login) {
        //handle some other stuff
        someFunction();
        latch.countDown();

    }
});





public void someFunction()[
   try {
    latch.await();
} catch (InterruptedException e) {
    e.printStackTrace();
}
  }
like image 114
Dishonered Avatar answered Mar 06 '26 15:03

Dishonered