A Kotlin Multiplatform (KMP) showcase focusing on industrial-grade HttpClient configuration. This project demonstrates how to offload common networking concerns—authentication, retries, logging, and serialization—to Ktor's powerful plugin architecture.
"One client, configured once, shared as a singleton — the rest of the code never has to think about auth headers, retry logic, or JSON parsing. That's the pit crew doing its job."
This demo centralizes network logic in HttpClientFactory.kt, implementing a robust pipeline of plugins:
- 📋 Dynamic Logging: Uses
LogLevel.ALLin debug for full visibility into request/response bodies, andLogLevel.NONEin production for zero overhead. - 🔄 Content Negotiation: Powered by
kotlinx.serializationwith lenient JSON parsing to survive minor backend inconsistencies and future-proof against new fields. - 🔐 Transparent Auth (Bearer):
- Auto-loading: Attaches tokens automatically to outgoing requests.
- Auto-refresh: Intercepts
401 Unauthorizedresponses, refreshes tokens viaTokenStorage, and retries the original request without any manual intervention in repositories. - Exclusion logic: Smartly skips authentication for specific endpoints (e.g., login/register).
- 🌐 Centralized Defaults: Sets the base URL (
JSONPlaceholder) and default headers (Content-Type,Accept) globally. - 🔁 Intelligent Retries:
- Automatically retries safe (idempotent) methods (GET, PUT, DELETE).
- Implements Exponential Back-off (2s → 4s → 8s) to handle transient server errors (5xx).
- Intentionally excludes POST requests to prevent accidental duplicate resource creation.
shared/commonMain:network/HttpClientFactory.kt: The heart of the networking layer.network/TokenStorage.kt: Contract for token management.network/PostsRepository.kt: Clean, logic-free data fetching.App: Compose Multiplatform UI demonstrating the network state.
- Kotlin Multiplatform (KMP)
- Ktor 3.1.3: Core networking engine.
- Compose Multiplatform: Shared UI layer.
- Kotlinx Serialization: JSON processing.
- Material 3: Modern UI components.
- Android Studio Ladybug (or newer)
- Kotlin 2.1.0+
- macOS (if running the iOS target)
- Android: Select the
androidAppconfiguration and hit Run. - iOS: Open the
iosAppfolder in Xcode or run from Android Studio using the KMP plugin.
- Toggle Debug Mode in the UI to see how
LoggingandprettyPrintbehavior changes in the Logcat. - Check
HttpClientFactory.ktto modify retry counts or base URLs.
This demo is part of an article series on advanced Kotlin Multiplatform networking. For a deep dive into the implementation details, check out the full post.