1 of 11

Bye Retrofit,

Hi Ktor

By Moro

2 of 11

We need to migrate the Android native app to be a KMP app…

Let’s start migrating Retrofit to Ktor…

3 of 11

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" }

4 of 11

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"]

5 of 11

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)

...

}

6 of 11

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

}

)

}

}

}

7 of 11

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

}

)

}

}

}

8 of 11

3. Update Response objects

9 of 11

4. Server call - ApiService.kt

10 of 11

5. Repository update

We just need to replace to our new implementation using Ktor

11 of 11