Connect with us

Articles

No more Retrofit, move to Ktor on Android

Waiting for the stable release of KMM (Kotlin Multiplatform Mobile) it could be useful starting to use this library instead of Retrofit. Let’s see how to configure it.

How to say the documentation, Ktor is an asynchronous framework for creating microservices, web applications and more. It is possible to use it to create a REST Client for yours Android applications.

Before to continue, Retrofit is still a good framework to make API calls, in this article I’m just suggesting another good framework that uses Kotlin libraries.

Waiting for the stable release of KMM (Kotlin Multiplatform Mobile) it could be useful starting to use this library instead of Retrofit. Let’s see how to configure it.

Dependencies

First, add the following dependencies in build.gradle:

def ktor_version = '1.5.1'
implementation "io.ktor:ktor-client-json:$ktor_version"
implementation "io.ktor:ktor-client-serialization-jvm:$ktor_version"
implementation "io.ktor:ktor-client-android:$ktor_version"

Also, you have to add Kotlin serialization library, adding in your classpath:

buildscript {
    ext.kotlin_version = '1.6.10'
    repositories { mavenCentral() }

    dependencies {
        classpath "org.jetbrains.kotlin:kotlin-serialization:$kotlin_version"
    }
}

And apply the plugin:

plugins {
    id 'kotlinx-serialization'
}

Client

Now, it’s time to configure your client, if you are using dependency injection you can create a Network module to implement Ktor client:

fun provideHttpClient(): HttpClient {
    return HttpClient(Android) {
        engine {
            connectTimeout = 30_000
            socketTimeout = 30_000
        }
        install(JsonFeature) {
            serializer = KotlinxSerializer(
                Json {
                    ignoreUnknownKeys = true
                    isLenient = true
                }
            )
        }
    }
}

You can configure your engine parameters, in this case connectTimeout is max milliseconds to establish an HTTP connection and socketTimeout is max milliseconds between TCP packets.

Talking about serialization, you have to configure a plugin to serialize JSON response, as you do on Retrofit with Moshi or Gson. So on serializer property, you will set the serializer that will be used for serializing requests and deserializing response bodies, in this case kotlin-serializer. In Json lambda, you can set some properties, in this case:

  • ignoreUnknownKeys specifies whether encounters of unknown properties in the input JSON should be ignored instead of throwing SerializationException.
  • isLenient makes parser more liberal to the malformed input. In lenient mode, quoted boolean literals, and unquoted string literals are allowed.

Models

To map models, it is necessary adding the annotation @Serializable, if you want to map your JSON property with different name you can annotate property using @SerialName("json_name")

@Serializable
data class Hotel(
    val id: Long,
    val name: String,
    val location: Location,
    val stars: Int,
    val checkIn: RangeHours,
    val checkOut: RangeHours,
    val contact: Contact,
    val gallery: List<String>,
    val userRating: Double,
    val price: Double,
    val currency: String
)

API

Finally, you can call your API using the httpClient defined before:

httpClient.get<List<Hotel>>(“your_url)

httpClient defines all HTTP request, in this case we are calling a GET with the specified your_url as URL, and it returns a List<Hotel> .

Full Article: Barros @ Medium
👋: 102
May 9, 2022
Advertisement

Trending