Create a custom completion / callback handler to return objects after the HTTP request has 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 this in Java.

Sorry if this question is too noob for StackOverflow people.

Problem

I am creating a class to handle my entire Http request, which is executed using Retrofit.

I make this function 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 this way: MainActivity

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

Now the function is still invalid, but I would like it to return something after the onResponse and onFailure .

Any thoughts please?

+5
source share
1 answer

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

And implement the interface when calling the method from MainActivity and use the response parameter in the onXXX() method as the data returned to update the interface.

+1
source

Source: https://habr.com/ru/post/1238342/


All Articles