Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retrofit return boolean value

I want to run changesHasBeenSaved if saveChanges function gives me true value. How can I get boolean or string or integer, any value, when Retrofit finish? Is it possible?

I need a function similar this:

public boolean saveChanges()
{
    Boolean output = false;
    RequestAPI requestAPI = Requests.getRetrofit();
    Call<Object> jsonObjectCall = requestAPI.readAllCategoeies();

    jsonObjectCall.enqueue(new Callback<Object>() {
        @Override
        public void onResponse(Call<Object> call, Response<Object> response) {
            if(response.body() != null) {
                output = true;
            }

        }

        @Override
        public void onFailure(Call<Object> call, Throwable t) {
            call.cancel();
        }
    });

    return output;
}
like image 984
Ulugbek Nuriddinov Avatar asked Apr 12 '26 12:04

Ulugbek Nuriddinov


1 Answers

You should change method return type boolean to void as retrofit work asynchronous.

You should pass the listener/callback to get the status in callback.

First create callback interface like below

public interface ApiCallback {
   void onResponse(boolean success);
}

Here how saveChanges will look like

public void saveChanges(final ApiCallback callback)
{
    RequestAPI requestAPI = Requests.getRetrofit();
    Call<Object> jsonObjectCall = requestAPI.readAllCategoeies();
    jsonObjectCall.enqueue(new Callback<Object>() {
        @Override
        public void onResponse(Call<Object> call, Response<Object> response) {
            callback.onResponse(response.body() != null);
        }

        @Override
        public void onFailure(Call<Object> call, Throwable t) {
            call.cancel();
            callback.onResponse(false);
        }
    });
}

Then you need to call saveChanges method like below

saveChanges(new ApiCallback () {
   public void onResponse(boolean success){
        if(success){
          // do something
        } else{
          // do something
        }
   }
});
like image 197
Krishna Sharma Avatar answered Apr 14 '26 00:04

Krishna Sharma



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!