Implement Robust Android Retrofit Services
A skill for production-grade Android Retrofit services - auth interceptors, typed error handling, and a tested repository pattern.
Why it matters
Implement and optimize Android Retrofit services for robust API communication. This asset provides expert guidance on structuring services, configuring OkHttp, and handling errors for reliable mobile application development.
Outcomes
What it gets done
Structure Retrofit services with separation of concerns.
Configure Retrofit with best practices for timeouts and interceptors.
Implement advanced interceptor patterns for authentication and error handling.
Develop comprehensive error handling and response wrapping strategies.
Install
Add it to your toolbox
Run in your project directory:
curl -fsSL https://spark.entire.vc/get/vb-android-retrofit-service | bash Overview
Android Retrofit Service Expert агент
This skill implements Android Retrofit services with auth-token-refresh interceptors, typed error handling via a sealed ApiResult class, validated request models, and a tested repository pattern. Use it when building or hardening the networking layer of an Android app, not for a quick one-off API call without auth or error handling.
What it does
This skill implements production-grade Android Retrofit services with a clear separation of concerns: an API interface using suspend functions annotated with @GET, @POST, @PUT, and @DELETE (path parameters, request bodies, and a Response<T> wrapper), and a repository layer that wraps each call in a try/catch and returns a Result<T> or a typed ApiResult sealed class (Success, Error, Loading) with onSuccess/onError extension functions. Network configuration follows a fixed pattern: an OkHttpClient with 30-second connect, read, and write timeouts, an auth interceptor, a logging interceptor, and a custom interceptor that adds Accept and Content-Type JSON headers, wired into a Retrofit builder with a base URL, the OkHttp client, and a Gson converter factory.
When to use - and when NOT to
Use it when building or hardening the networking layer of an Android app - auth token handling, error typing, retries, and testable repositories - not for a quick one-off API call without auth or error handling. It is not a substitute for API design: it assumes a REST API already exists and focuses on the client-side architecture around it.
Inputs and outputs
Given an API contract, it produces two interceptors (an AuthInterceptor that attaches a bearer token to every request and, on a 401 response, synchronously refreshes the token and retries with the new one, and a NetworkErrorInterceptor that maps response codes to typed exceptions - 429 to a RateLimitException, 500-599 to a ServerException - and wraps IOException as a NetworkException), request and response models (a User data class and a CreateUserRequest with constructor-level validation requiring a non-blank email and name and an 8+ character password, both using Gson's SerializedName annotations, plus a generic ApiResponse wrapper for data, message, and errors), and a test suite pattern covering both a mocked-success case asserting result.isSuccess and a mocked-IOException case asserting result.isFailure and the correct exception type.
@Singleton
class NetworkModule {
@Provides
@Singleton
fun provideOkHttpClient(
authInterceptor: AuthInterceptor,
loggingInterceptor: HttpLoggingInterceptor
): OkHttpClient {
return OkHttpClient.Builder()
.connectTimeout(30, TimeUnit.SECONDS)
.readTimeout(30, TimeUnit.SECONDS)
.writeTimeout(30, TimeUnit.SECONDS)
.addInterceptor(authInterceptor)
.addInterceptor(loggingInterceptor)
.addInterceptor { chain ->
val request = chain.request().newBuilder()
.addHeader("Accept", "application/json")
.addHeader("Content-Type", "application/json")
.build()
chain.proceed(request)
}
.build()
}
@Provides
@Singleton
fun provideRetrofit(okHttpClient: OkHttpClient): Retrofit {
return Retrofit.Builder()
.baseUrl(BASE_URL)
.client(okHttpClient)
.addConverterFactory(GsonConverterFactory.create())
.build()
}
@Provides
@Singleton
fun provideUserApiService(retrofit: Retrofit): UserApiService {
return retrofit.create(UserApiService::class.java)
}
}
Integrations
Built on OkHttp and Gson underneath Retrofit, with a set of performance practices: OkHttp's own response cache and connection pooling with HTTP/2 support, request deduplication for identical concurrent calls, custom Gson TypeAdapters for complex serialization, API-specific timeout tuning, exponential-backoff retry logic for transient failures, the @Streaming annotation for large file downloads, and coroutine suspend functions throughout for async handling.
Who it's for
Android developers building or maintaining the networking layer of an app who need auth-token refresh, typed error handling, and a tested repository pattern rather than raw, unguarded API calls.
FAQ
Common questions
Discussion
Questions & comments · 0
Sign In Sign in to leave a comment.