Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retrofit: How to wait for response

I have AsyncTask and the doInBackground method inside which, I sending POST request using Retrofit. My code looks like:

    //method of AsyncTask
    protected Boolean doInBackground(Void... params) {
        Retrofit restAdapter = new Retrofit.Builder()
                .baseUrl(Constants.ROOT_API_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        IConstructSecureAPI service = restAdapter.create(IConstructSecureAPI.class);
        //request
        Call<JsonElement> result = service.getToken("TestUser", "pass", "password");
        result.enqueue(new Callback<JsonElement>() {
            @Override
            public void onResponse(Call<JsonElement> call, Response<JsonElement> response) {

            }

            @Override
            public void onFailure(Call<JsonElement> call, Throwable t) {

            }
        });

        return true;
    }

The problem is: Retrofit sending request asynchronously and while it, the doInBackground method returning the value. So I need to send a request in the same thread with all executions in the sequence. One by one. And returning from doInBackground occurs after the request finished. How can I send a request in the same thread using Retrofit?

like image 624
kkost Avatar asked Feb 25 '16 22:02

kkost


People also ask

What is callback in retrofit?

Interface Callback<T>Communicates responses from a server or offline requests. One and only one method will be invoked in response to a given request. Callback methods are executed using the Retrofit callback executor.

What is enqueue in retrofit?

enqueue(Callback<T> callback) Asynchronously send the request and notify callback of its response or if an error occurred talking to the server, creating the request, or processing the response. Response<T> execute() Synchronously send the request and return its response.


1 Answers

The Call class has an execute() method that will make your call synchronously.

enqueue() is explicitly for making an asychronous call.

like image 168
Bryan Herbst Avatar answered Sep 21 '22 02:09

Bryan Herbst