Short answer
It turns Java/Kotlin interfaces into HTTP requests through dynamic proxies; the Converter converts JSON to objects, while the CallAdapter converts the return type to other types such as RxJava Single or a custom Result; suspend functions are natively supported since Retrofit 2.6 without a CallAdapter.
Explanation
Retrofit uses the OkHttp library as its internal network client. When the API function is called, the Converter.Factory (such as Moshi or Kotlinx.Serialization) converts the request and response body to and from JSON text. CallAdapter.Factory lets the function return custom types other than Call<T> (such as Observable or Single in RxJava, or a custom Result wrapper). Support for the suspend keyword is built into Retrofit itself since version 2.6, as is returning Response<T>, with no need for any additional CallAdapter.
Code example
interface UserApiService {
@GET("users/{id}")
suspend fun getUser(@Path("id") userId: String): UserDto
}
val retrofit = Retrofit.Builder()
.baseUrl("https://api.example.com/")
.addConverterFactory(Json.asConverterFactory("application/json".toMediaType()))
.build()Common mistakes
- Forgetting to add a trailing slash (/) to the baseUrl, which leads to an IllegalArgumentException when creating Retrofit.
- Running the old synchronous API calls (call.execute()) on the main thread, causing NetworkOnMainThreadException.