Simple implementation of Ktor Http Client for Android with Kotlin Serialization. The project is using the free api from thecocktaildb for providing data.
Ktor is an open-source framework built by JetBrains for building asynchronous servers and clients using Kotlin programming language.
- Add plugin
id("kotlinx-serialization")
- Add Dependencies
plugins {
...
id("kotlinx-serialization")
}
implementation(platform("io.ktor:ktor-bom:3.0.1"))
implementation("io.ktor:ktor-client-android")
implementation("io.ktor:ktor-client-serialization")
implementation("io.ktor:ktor-client-logging")
implementation("io.ktor:ktor-client-content-negotiation")
implementation("io.ktor:ktor-serialization-kotlinx-json")
- Add Kotlin Serialization plugin
id("org.jetbrains.kotlin.plugin.serialization") version "2.0.21"
private const val NETWORK_TIME_OUT = 6_000L
val httpClientAndroid = HttpClient(Android) {
install(ContentNegotiation) {
json(
Json {
prettyPrint = true
isLenient = true
useAlternativeNames = true
ignoreUnknownKeys = true
encodeDefaults = false
}
)
}
install(HttpTimeout) {
requestTimeoutMillis = NETWORK_TIME_OUT
connectTimeoutMillis = NETWORK_TIME_OUT
socketTimeoutMillis = NETWORK_TIME_OUT
}
install(Logging) {
logger = object : Logger {
override fun log(message: String) {
Log.v("Logger Ktor =>", message)
}
}
level = LogLevel.ALL
}
install(ResponseObserver) {
onResponse { response ->
Log.d("HTTP status:", "${response.status.value}")
}
}
install(DefaultRequest) {
header(HttpHeaders.ContentType, ContentType.Application.Json)
}
defaultRequest {
contentType(ContentType.Application.Json)
accept(ContentType.Application.Json)
}
}
- Koin - Koin is a pragmatic and lightweight dependency injection framework for Kotlin developers
- Jetpack Compose - Android’s modern toolkit for building native UI.
- Coroutines and Flow - Official Kotlin's tooling for performing asynchronous work.
- ViewModel - The ViewModel is designed to store and manage UI-related data in a lifecycle conscious way.
- StateFlow - StateFlow is a state-holder observable flow that emits the current and new state updates to its collectors.