Android Development

Issue Tracker Android Updates Android Home Home Contact

What is Retrofit?

Retrofit is a Java library that helps Kotlin and Java applications (running on the JVM) perform HTTP communication with web services, especially those following the REST architecture. Although not limited to Android, Retrofit is most commonly used in Android development due to its simplicity and strong integration with other Android libraries. It allows developers to define network requests using interface methods that describe the request type and expected response. This use of interfaces simplifies the code, as only method signatures are needed and Retrofit generates the necessary implementation. Internally, Retrofit relies on OkHttp to handle network connections and data transmission.

Why use Retrofit over HttpURLConnection and OkHttp directly?

While HttpURLConnection and OkHttp provide low-level APIs to make HTTP calls, they require manual handling of request setup, threading, error management, and JSON parsing. Retrofit abstracts these complexities:

  • HttpURLConnection is low-level and verbose.
  • OkHttp is powerful but still requires boilerplate.
  • Retrofit builds on top of OkHttp, adding features like request annotations, automatic deserialization (e.g., with Gson or Moshi), and support for different call adapters (e.g., coroutines, RxJava).

Key Features of Retrofit

  • Annotation-based API declaration using @GET, @POST, etc.
  • Automatic JSON serialization/deserialization via converters
  • Custom CallAdapter support for Coroutines, RxJava, etc.
  • Built-in error handling and HTTP response code inspection
  • Support for form-encoded and multipart requests

Comparison with Networking Library Volley

Volley is a popular networking library developed by Google specifically for Android. It is designed to handle asynchronous network operations with built-in features such as request queuing, prioritization, caching, and image loading. Volley simplifies common networking tasks and is particularly suited for smaller requests and frequent image loading in Android apps.

Retrofit vs Volley

Aspect Retrofit Volley
Request Declaration Interface-based, annotation-driven Programmatic request objects
Serialization Built-in with Gson/Moshi Manual or third-party JSON parsing
Threading Coroutine/RxJava integration Handles threading internally
Image loading Requires external library (e.g., Glide) Built-in image caching and loading
Ease of use Simple and clean interface More control but verbose

How Retrofit Works Inside a Coroutine

When calling a Retrofit suspend function inside a coroutine, the call does not block the thread. Instead:

  • The suspend function delegates the request to Retrofit’s Coroutine CallAdapter.
  • The CallAdapter converts this into an asynchronous OkHttp network request.
  • The coroutine is suspended and the current thread is freed to do other work.
  • OkHttp executes the HTTP request on a background thread.
  • Once the network response arrives, the coroutine is resumed with the result or an exception if the call failed.

So inside the suspend function, Retrofit is effectively wrapping the OkHttp asynchronous callback into a coroutine suspension/resumption mechanism, making the network call appear as a simple sequential function call.

This flow makes asynchronous network requests look like simple, sequential code, while efficiently using threads and resources under the hood.

val retrofit = Retrofit.Builder()
    .baseUrl("https://api.example.com/")
    .addConverterFactory(GsonConverterFactory.create())
    .addCallAdapterFactory(CoroutineCallAdapterFactory())  // or use built-in support
    .build()

val apiService = retrofit.create(ApiService::class.java)

suspend fun fetchUser(userId: Int): User? {
    val response = apiService.getUser(userId)
    if (response.isSuccessful) {
        return response.body()
    } else {
        throw Exception("Network call failed with code ${response.code()}")
    }
}