Bye Retrofit,
Hi Ktor
By Moro
We need to migrate the Android native app to be a KMP app…
Let’s start migrating Retrofit to Ktor…
1. Add library to the libs.versions.toml
[versions]
ktor = "2.3.9"
kotlinx-serialization-json = "1.6.3"
[libraries]
kotlinx-serialization-json = { module = "org.jetbrains.kotlinx:kotlinx-serialization-json", version.ref = "kotlinx-serialization-json" }
ktor_client_core = { group = "io.ktor", name = "ktor-client-core", version.ref = "ktor" }
ktor_client_okhttp = { group = "io.ktor", name = "ktor-client-okhttp", version.ref = "ktor" }
ktor_client_content_negotiation = { group = "io.ktor", name = "ktor-client-content-negotiation", version.ref = "ktor" }
ktor_serialization_kotlinx_json = { group = "io.ktor", name = "ktor-serialization-kotlinx-json", version.ref = "ktor" }
1. Add library to the libs.versions.toml
[plugins]
serialization = { id = "org.jetbrains.kotlin.plugin.serialization", version.ref = "kotlin" }
[bundles]
ktor = ["ktor_client_core", "ktor_client_okhttp", "ktor_client_content_negotiation", "ktor_serialization_kotlinx_json"]
2. Add new dependencies to data module
Sir, what is data module?
It is the module where have the communication between the app and the server. The Retrofit code is there.
plugins {
alias(libs.plugins.serialization)
...
}
dependencies {
implementation(libs.bundles.ktor)
implementation(libs.kotlinx.serialization.json)
...
}
2. Create the HttpClient in DataModule.kt
We can use the same interceptors, because we will use OkHttp as client engine
single {
HttpClient(
engine = OkHttpEngine(
config = OkHttpConfig().apply {
addInterceptor(AuthenticationInterceptor(get(named("api_token"))))
addInterceptor(LoggedInterceptor())
}
)
) {
install(ContentNegotiation) {
json(
json = Json {
ignoreUnknownKeys = true
}
)
}
}
}
2. Create the HttpClient in DataModule.kt
Install the ContentNegotiation
single {
HttpClient(
engine = OkHttpEngine(
config = OkHttpConfig().apply {
addInterceptor(AuthenticationInterceptor(get(named("api_token"))))
addInterceptor(LoggedInterceptor())
}
)
) {
install(ContentNegotiation) {
json(
json = Json {
ignoreUnknownKeys = true
}
)
}
}
}
3. Update Response objects
4. Server call - ApiService.kt
5. Repository update
We just need to replace to our new implementation using Ktor