Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a Custom Completion/Callback Handler to return Objects after a HTTP Request is Completed

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("[email protected]");

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?

like image 681
JayVDiyk Avatar asked Dec 16 '15 06:12

JayVDiyk


1 Answers

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.

like image 122
SamMao Avatar answered Oct 19 '22 16:10

SamMao