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

1

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("[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?

Undersea answered 16/12, 2015 at 6:29 Comment(1)
#53979980 Check this postUnbar
K
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.

Kingcraft answered 16/12, 2015 at 6:43 Comment(3)
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.Undersea
@Undersea You can do something like: public void checkEmailAvailability (String email, final Callback<RestOauth> listener) and onResponse if (listener != null) { listener.success(retrofit, response); } onFailure if (listener != null) { listener.failure(t);Herby
@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?Undersea

© 2022 - 2024 — McMap. All rights reserved.