How to return a value using Async Retrofit 2.0

I am new to modernization, I have a function with Async update, with the goal 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 do not know how to return this value.

+4
source share
1 answer

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

try something like:

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

your method should look like this:

 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 need to pass one callback instance.

+13
source

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


All Articles