6

I am an iOS Developer starting to learn Android. In Swift, creating a completion handler is very simple, but I still can't find a way to do it in Java.

I am sorry if this question is too noob for StackOverflow people.

Problem

I am creating a class to handle all my Http Request which is done using Retrofit.

I make this function is my RequestHelper.java

public static void checkEmailAvailability(String email) {
    MyWebServiceAPI serviceAPI = retrofit.create(MyWebServiceAPI.class);

    Call<APIResults> call = serviceAPI.checkEmailAvailability(getAuthenticationHeader(), RequestBody.create(MediaType.parse("text/plain"), email));

    call.enqueue(new Callback<APIResults>() {
        @Override
        public void onResponse(retrofit.Response<APIResults> response, Retrofit retrofit) { 
              //Parse Response Json
              //Get some value and place it inside an object
             //ANDI WOULD LIKE RETURN SOME BOOLEAN VALUE AND SOME OTHER STRING
        }

        @Override
        public void onFailure(Throwable t) {
              //I WOULD LIKE A BOOLEAN VALUE HERE            
        }
    });
}

I call it like this from my MainActivity

RequestHelper.checkEmailAvailability("user@user.com");

Now the function is still void but I would like for it to return something after the on the onResponse and onFailure method.

Any thoughts please?

JayVDiyk
  • 4,277
  • 22
  • 70
  • 135
  • https://stackoverflow.com/questions/53979480/replicating-swift-completion-handler-on-android-java Check this post – AD Progress Aug 31 '21 at 10:42

1 Answers1

1

You should pass the Callback object as a parameter to the checkEmailAvailability().

And implement the interface when you call the method from your MainActivity,and use the response parameter in the onXXX() method as the data returned to update UI.

SamMao
  • 181
  • 12
  • I would like to have a different Callback (Custom). Because I am gonna parse the response and the return the value of it in a Callback. – JayVDiyk Dec 16 '15 at 06:56
  • @JayVDiyk You can do something like: public void checkEmailAvailability (String email, final Callback listener) and onResponse if (listener != null) { listener.success(retrofit, response); } onFailure if (listener != null) { listener.failure(t); – JoCuTo Dec 16 '15 at 07:13
  • @JeCuRo Thanks for replying. Let's say. I want to return a boolean value in the Callback. How would I go about to do it? – JayVDiyk Dec 16 '15 at 08:47