Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return value using Async Retrofit 2.0

I am new with retrofit, i have a function with Async Retrofit, with purpose like this example

public boolean bookmark(){
   boolean result = false;

   Call<Response> call = service.bookmark(token, request);
   call.enqueue(new Callback<Response>() {

      @Override
            public void onResponse(Call<Response> call, retrofit2.Response<Response> response) {
            result = true;
      }
      @Override
            public void onFailure(Call<Response call, Throwable t) {

      }
   });

   return result;
}

but i dont know how to return that value.

like image 460
wanz Avatar asked May 10 '16 14:05

wanz


1 Answers

You can use a custom interface. If you pass the interface as parameter to the method "bookmark", you can use it.

try something like:

public interface BookmarkCallback{
      void onSuccess(boolean value);
      void onError();
}

your method should look like:

public void bookmark(final BookmarkCallback callback){
     Call<Response> call = service.bookmark(token, request);
     call.enqueue(new Callback<Response>() {
        @Override
        public void onResponse(Call<Response> call, retrofit2.Response<Response> response) {
             callback.onSuccess(true);
       }

       @Override
       public void onFailure(Call<Response call, Throwable t) {
           callback.onError();
       }
});

When you call this method, you have to pass one callback instance.

like image 137
asanchezyu Avatar answered Oct 14 '22 07:10

asanchezyu