Retrofit
Retrofit is a popular open-source library developed by Square, Inc. that simplifies the process of making network requests in Android and Java applications. It provides a type-safe and asynchronous API for interacting with REST APIs.
Usage
Dependencies
Within your app
module’s build.gradle.kts
file, incorporate the following dependencies:
implementation(project(":networking:retrofit"))
Example
This documentation guides you through using the RetrofitClient
class, designed to interact seamlessly with an API.
Since RetrofitClient
is an abstract class, you’ll need to create a concrete subclass tailored to your API’s configuration. Here’s a breakdown of the key steps:
Creating a Retrofit client
class MyRetrofitClient: RetrofitClient() {
override val baseUrl: String = ""
// Optional access token retrieval function if your API requires it
// For example to get it from your DataStore Preferences or Shared Preferences
override val accessToken: (suspend () -> String)? = null
override val timeoutMillis: Long = 30000 // Adjust timeout as needed
override val isLoggingEnabled: Boolean = true // Enable or disable logging
}
- Provide the base URL of your API in the
baseUrl
property. - Provide a function for retrieving an access token (if applicable) in the
accessToken
property. - Adjust the
timeoutMillis
value to suit your needs. - Set
isLoggingEnabled
to true or false for detailed logging.
Performing a request
The doRequest
method provides a convenient way to execute requests to your API. Here’s how to use it:
interface UserService {
@GET("users")
fun getUsersWithCall(): Call<List<UserResponse>>
@GET("users")
suspend fun getUsersWithResponse(): Response<List<UserResponse>>
}
val client = MyRetrofitClient()
suspend fun getUsersWithCall(): NetworkResponse<List<UserResponse>> {
return client.doRequest(client.getService<UserService>().getUsersWithCall())
}
suspend fun getUsersWithResponse(): NetworkResponse<List<UserResponse>> {
return client.doRequest(client.getService<UserService>().getUsersWithResponse())
}
The doRequest
method handles various aspects:
- Automatically includes the access token in the Authorization header if a retrieval function is provided.
- Encodes request payloads in JSON format using the pre-configured JSON serializer.
- Decodes JSON responses from the API.
- Catches and handles exceptions for network errors and serialization issues.
It returns a NetworkResponse
sealed class, which can either be a Success
containing the parsed response data or an Error
representing different failure scenarios. You’ll need to handle the specific response type based on your API’s response format (e.g., UserResponse in this example).
Additional Considerations
- Error Handling: The provided code demonstrates basic error handling. You might want to customize it further to cater to your specific requirements, such as logging errors or retrying requests upon certain error conditions.
- Advanced Retrofit Features: Retrofit offers a wide range of features, such as custom converters, interceptors, and more. You can explore these features to enhance your API interactions further.
More information on Retrofit can be found in the official documentation .