Integration
To integrate ktor into the project add the following lines under the dependencies node in the app module and other modules where you might have to make the network calls.
// Ktor
implementation("org.jetbrains.kotlinx:kotlinx-serialization-json:1.3.2")
implementation("io.ktor:ktor-client-core:2.3.12")
// CIO - for JVM and Android
implementation("io.ktor:ktor-client-cio:2.3.12")
implementation("io.ktor:ktor-client-content-negotiation:2.3.12")
implementation("io.ktor:ktor-serialization-kotlinx-json:2.3.12")
Then add the following line under the plugins section in the project-level gradle file.
id 'org.jetbrains.kotlin.plugin.serialization' version '1.9.23' apply false
Now add the following lines in app/proguard-rules.pro
to make sure Ktor works as expected in release builds even with obfuscation.
# Ktor
-keep class io.ktor.** { *; }
-keep class kotlinx.coroutines.** { *; }
-dontwarn kotlinx.atomicfu.**
-dontwarn io.netty.**
-dontwarn com.typesafe.**
-dontwarn org.slf4j.**
Then remove all the Retrofit-related dependencies and hit the sync now button.
DI Migration
Now we need to update the Koin network and data source modules, replacing the Retrofit with Ktor. Let’s start with the network module, The following is the Retrofit setup of the network module.
val networkModule = module {
single<Gson> { GsonFactory.create() }
single<Converter.Factory> { GsonConverterFactory.create(get()) }
single<OkHttpClient> {
OkHttpClientFactory.create()
}
single<Retrofit> {
RetrofitFactory.create(
okHttpClient = get(),
converterFactory = get(),
)
}
}
After migration to Ktor, it looks as follows:
val networkModule = module {
single<Json> {
Json {
ignoreUnknownKeys = true
isLenient = true
prettyPrint = true
encodeDefaults = true
}
}single<HttpClient> {
HttpClient(CIO) {
install(ContentNegotiation) {
get<Json>()
}
}
}
}
Now we need to replace the retrofit inject with the Ktor client, as I’ve a single API in the application, I’m replacing the retrofit service interface with Kotr client and requesting with the client directly. But the real-time use of Ktor will be much more complicated with multiple routes and header configuration for which please refer to this article.
Before:
class WizardRemoteDataSource constructor(
private val api: RetrofitServiceApi,
): WizardDataSource
After:
class WizardRemoteDataSource constructor(
private val httpClient: HttpClient,
): WizardDataSource
That’s all, now the project network module is compatible with kotlin multiplatform.