How to return value using Async Retrofit 2.0

末鹿安然 提交于 2019-12-21 04:26:08

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/37141013/how-to-return-value-using-async-retrofit-2-0

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!