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

2

Hello friends I have the following method that requests 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 every time. I need it to return the value that comes from the server, that is, that it waits for the request and returns "iten". Is it possible?

    
asked by anonymous 03.11.2018 / 14:56

1 answer

3

No (1) , it is not possible.

"Calls" executed by Retrofit have the result returned asynchronously.

The result is obtained in the onResponse() method or, if there is an error, in the onFailure() method, from the Callback interface implementation passed to enqueue() method.

(1) Well, until it's possible > if the targetSdkVersion is less than 4.0. In equal or higher versions, the NetworkOnMainThreadException exception is thrown.

    
03.11.2018 / 15:11