How to make a method wait for the java server response using Retrofit2?

Asked

Viewed 112 times

2

Hello friends I have the following method that requests to the server:

public MetaDataR metodo1(final String m) {
            Call<MetaDataR> call2 = new RetrofitConfig().getMetasService().getMetas(m);
            call2.enqueue(new Callback<MetaDataR>() {
                @Override
                public void onResponse(@NonNull Call<MetaDataR> call, @NonNull Response<MetaDataR> response) {
                    if (response.body() != null) {
                        MetaDataR iten = response.body();      ////Quero retornar "iten" para o metodo1()                       

                        }
                    }
                }

                @Override
                public void onFailure(@NonNull Call<MetaDataR> call, @NonNull Throwable t) {
                    // tratar algum erro
                    Log.e("Erro", "Erro ao buscar:" + t.getMessage());
                }
            });
            return null;
        }

This way it returns NULL always. I need it to return the value that comes from the server, that is to wait for the request and return "iten". It is possible?

1 answer

3


Not(1), is not possible.

The "calls" executed by Retrofit have the result returned asynchronously.

The result is obtained in the method onResponse() or, in case of error, in the method onFailure(), implementation of the interface Callback passed to the method enqueue().

(1) Well, it’s even possible if the targetSdkVersion is less than 4.0. In equal or higher versions the exception Networkonmainthreadexception.

  • Okay, thanks @ramaral, I’ll digest that is trying another alternative.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.