How to make a synchronous call using Retrofit on Android

9.7k Views Asked by At

I have a login view in an android app that I would like to function synchronously. That is, I want the user to stay on the page until the login rest call completes. If it fails, the user can reenter their id and password. If it is successful they are routed to a welcome page.

Retrofit gives examples of how to make synchronous calls. But it comes with a warning that "synchronous requests trigger app crashes on Android 4.0 or newer. You’ll run into the NetworkOnMainThreadException error." I've seen various responses on stackoverflow including using Otto and Robospice. Others to use homegrown listeners and others to use synchronous requests.

What would be the easiest, safest way to implement this functionality.

3

There are 3 best solutions below

8
ashkhn On

You don't need synchronous requests to achieve this..

Synchronous requests are carried out on the main thread. In android the main thread is used for drawing your UI so carrying out a network request on that thread will block your UI hence Android raises an exception .

Asynchronous requests carry out the networking in a separate thread and have callbacks to deliver information back to the main thread. This is what you need.

Here's what the sample code using Retrofit would look like in your case

call.enqueue(new Callback<LoginResponse>() {  
    @Override
    public void onResponse(Call<LoginResponse> call, Response<LoginResponse> response) {
        if (response.isSuccessful()) {
            // status code 2xx. start welcome activity
        } else {
            // Recieved a response but not 2xx. 
            // Possibly authentication error. Show error message

        }
    }

    @Override
    public void onFailure(Call<LoginResponse> call, Throwable t) {
        // request could not be executed ( possibly no internet connection)

    }
}
0
Siva Kumar On

If you run synchronous calls in retrofit, app will crashes on Android 4.0 or newer. You’ll run into the NetworkOnMainThreadException error. Synchronous methods provide the ability to use the return value directly, because the operation blocks everything else during your network request.

For non-blocking UI, you have to handle the request execution in a separated thread by yourself. That means, you can still interact with the app itself while waiting for the response. Ref: enter link description here

0
Dmitry Bagrov On

You can do the following:

Response<T> response = call.execute();