Przejdź do treści
Biblioteka skilli
Programowanie · Budowanie i kod

android-retrofit

/android-retrofit

Pomaga pracować z Retrofit na Androidzie: definicje interfejsów usług, integracja z korutynami, konfiguracja OkHttp, moduły Hilt i obsługa błędów w warstwie repozytorium.

Repozytorium
android-skills ↗
Licencja
MIT
Ostatnia zmiana repozytorium
19.09.2026

Ocena i bezpieczeństwo

100/ 100Klasa: dobry
Format25 / 25
Frontmatter z nazwą i opisem, poprawna nazwa, opis do 1024 znaków, nazwa zgodna z folderem.
Odkrywalność25 / 25
Opis mówi, kiedy użyć skilla, ma sensowną długość i jest w 3. osobie.
Treść35 / 35
Co najmniej 150 słów i do 500 linii, nagłówki, listy kroków, przykłady albo kod.
Higiena15 / 15
Bez zaślepek typu TODO, bez ścieżek Windows, z licencją.
Ryzykobrak sygnałów w skanie
Pliki w paczce
1
Skrypty
0
Komentarze HTML
0
Adresy URL w SKILL.md
0
Przestarzałość

Brak sygnałów. Repozytorium zmienione 19.09.2026, bez odwołań do wycofanych modeli i API.

Licencja

MIT, otwarta: można używać i zmieniać, z zachowaniem informacji o autorze.

Co robi i kiedy

Pomaga pracować z Retrofit na Androidzie: definicje interfejsów usług, integracja z korutynami, konfiguracja OkHttp, moduły Hilt i obsługa błędów w warstwie repozytorium.

Oryginalny opis (EN)

Use when setting up or working with Retrofit in Android — service interface definitions, coroutines integration, OkHttp configuration, Hilt module setup, and error handling in the repository layer.

Jak działa

  1. Service interface
  2. OkHttp & JSON
  3. Auth: interceptor, and the throw-vs-proceed decision
  4. Error handling
  5. Checklist
Sekcje z nagłówków SKILL.md, w oryginale · 62 linii, 471 słów
Podgląd SKILL.md
---
name: android-retrofit
description: Use when setting up or working with Retrofit in Android — service interface definitions, coroutines integration, OkHttp configuration, Hilt module setup, and error handling in the repository layer.
---

# Android Networking with Retrofit

Modern Retrofit setup for Android using coroutines, `kotlinx.serialization`, and Hilt. This reference covers the decisions that are easy to get wrong, not the standard boilerplate of service interfaces, Hilt module wiring, and the converter setup.

## Service interface

Declare every endpoint as a `suspend` function. **Return the body type directly** — Retrofit throws `HttpException` on non-2xx, giving a clean `try/catch` at the repository boundary. Use `Response<T>` **only** when you need the status code, headers, or error body (e.g. server-side validation messages):

```kotlin
// Direct body — throws HttpException on non-2xx; the common case
@GET("users/{user}/repos")
suspend fun listRepos(@Path("user") user: String): List<Repo>

// Response wrapper — only when you need code/headers/error body
@GET("users/{user}")
suspend fun getUser(@Path("user") user: String): Response<User>
```

Wrapping every endpoint in `Response<T>` "just in case" forces callers to check `isSuccessful` and handle a nullable body even when only the body matters — don't.

## OkHttp & JSON

Standard wiring (in a Hilt `@Module`/`@Provides @Singleton`): `HttpLoggingInterceptor` with its level gated on `BuildConfig.DEBUG`, sensible connect/read timeouts, and the `kotlinx.serialization` converter (`json.asConverterFactory("application/json".toMediaType())`). For an API that's loose with its payloads, configure:

```kotlin
Json { ignoreUnknownKeys = true; coerceInputValues = true; isLenient = true }
```

## Auth: interceptor, and the throw-vs-proceed decision

Attach the token via an `Interceptor`, not a per-endpoint `@Header` — a single missed `@Header` parameter is an unauthenticated request that fails at runtime, not compile time. The part most often gotten wrong is **what to do when the token is absent**:

```kotlin
class AuthInterceptor @Inject constructor(
    private val tokenProvider: TokenProvider,
) : Interceptor {
    override fun intercept(chain: Interceptor.Chain): Response {
        val token = tokenProvider.getToken()
            ?: throw IOException("Auth token unavailable") // fail fast — see note below
        val request = chain.request().newBuilder()
            .header("Authorization", "Bearer $token")
            .build()
        return chain.proceed(request)
    }
}
```

> **Throw vs proceed:** **Throw** when all endpoints require auth — a missing token should surface immediately rather than silently producing a confusing 401. **Proceed without the header** only if the same `OkHttpClient` is shared between authenticated and public endpoints: `?: return chain.proceed(chain.request())`. Silently proceeding when every call needs auth is a common mistake.

## Error handling

The repository is the error boundary: catch `HttpException`/`IOException` there and map them to a domain error type — never let Retrofit/OkHttp exception types reach the ViewModel, and never expose Retrofit DTOs to it. Don't redefine the error hierarchy here; see `android-skills:android-data-layer` for the repository pattern and the shared `DataError` taxonomy.

## Checklist

- [ ] All service functions are `suspend`
- [ ] `Response<T>` only when you need the status code, headers, or error body
- [ ] `OkHttpClient` logging gated behind `BuildConfig.DEBUG`; sensible timeouts set
- [ ] Auth applied via an `Interceptor`, with the token-absent policy chosen (throw vs proceed)
- [ ] Network exceptions mapped to domain types at the repository; DTOs never reach the ViewModel

Wersje

W bazie nie ma innych skilli o nazwie android-retrofit.

Migawka bazy z 13.11.2026 · wersja paczki 15b0136d773b (skrót SHA-256 całej paczki)

Pobrania w ostatnich 30 dniach: 2 · ranking

Zgłoś problem z tym skillem: szkodliwa treść, błędny opis albo prośba autora o usunięcie.

Podobne skille

  • 90Android Networking
    Dodaje do aplikacji Android wywołania HTTP i API: OkHttp, Retrofit lub Ktor, z limitami czasu, ponowieniami i obsługą błędów.
  • 100android-network
    Podłącza Retrofit i OkHttp do istniejącego projektu Kotlin Android: typowane wyniki, mapowanie błędów i nagłówki tokenów.
  • 100android
    Odpowiada na pytania o programowanie na Androida: Kotlin, Jetpack Compose, architektura, MVVM, Clean Architecture, Room, Hilt, Retrofit i testowanie.
  • 100android-networking
    Integruje Retrofit, OkHttp i Kotlinx Serialization dla typowanej komunikacji z API w Android, w tym interceptory i bezpieczeństwo sieci.
  • 100kotlin-android
    Pomaga budować i naprawiać natywne aplikacje Android w Kotlinie i Jetpack Compose w warstwowej architekturze UDF: ViewModel, StateFlow, Hilt, Room, Retrofit, coroutines i Navigation.
  • 90android-architecture
    Pomaga ustawić i utrzymać nowoczesną architekturę aplikacji Android w Clean Architecture z Hiltem: strukturę projektu i moduły.

Uwagi i zgłoszenia

Wiadomość trafi do Bartosza Sokolińskiego. Adres e-mail jest potrzebny tylko do odpowiedzi. Szczegóły w polityce prywatności.