(KMM- Ktor) Multiplatform Networking

Codeangi
4 min readFeb 21, 2023
src: https://github.com/ktorio/ktor

Ktor is a framework to easily build connected applications — web applications, HTTP services, mobile and browser applications. Modern connected applications need to be asynchronous to provide the best experience to users, and Kotlin coroutines provide awesome facilities to do it in an easy and straightforward way. The goal of Ktor is to provide an end-to-end multiplatform framework for connected applications.”

Ktor for multiplatform

Using Ktor we can create our own HTTP client to interact with remote servers, typically we will be using a content negotiation & serialization plugin to parse Raw Network Response into a usable DTO. OkHttp is a popular network client used by the Android community extensively, it provides finer control over network interactions, similarly, darwin client is used in iOS/Native for network interactions.

What are network Engines?:

“The Ktor HTTP client can be used on different platforms, including JVM, Android, JavaScript, and Native. A specific platform may require a specific engine that processes network requests. For example, you can use Apache or Jetty for JVM applications, OkHttp or Android for Android, Curl for desktop applications targeting Kotlin/Native, and so on. Different engines may have specific features and provide different configuration options.”

Each engine comes with its own limitations and configurations some can be found here: Engines | Ktor

  • If an engine supports HTTP/2, you can enable it by customizing the engine configuration (see an example for the Java engine).
  • To configure SSL in the Ktor client, you need to customize the configuration of a selected engine.
  • Some engines don’t support proxy.
  • The Logging plugin provides different logger types for different platforms.
  • The HttpTimeout plugin has some limitations for specific engines.
  • The XML serializer is supported on JVM only.

Setting up Ktor with OkHttp Engine for Android:

A JVM/Android client engine that uses the OkHttp HTTP client. This engine supports Android 5.0 and newer.

To configure the engine, pass the settings exposed by OkHttpConfig to the engine method:

Setting up Ktor with Darwin Engine for iOS:

A Kotlin/Native client engine that targets Darwin-based operating systems (such as macOS, iOS, tvOS, and so on) and uses NSURLSession internally. To configure the engine, pass the settings exposed by DarwinClientEngineConfig to the engine method:

How to integrate Ktor into a KMM project:

In order to integrate Ktor into a KMM project, we need to add respective dependencies in build.gradle.kts file of the shared module/KMM Library.

Once the dependencies are set, its time to configure our network client, this is done by first declaring a expect function for HttpClient inside commonMain sourceSet (standard practice to do it in Platform.kt ), this will let us implement platform-specific implementation for OkHttp and Darwin network clients in androidMain and iosMain respectively.

commonMain→ Platform.kt

androidMain→ Platform.kt

iosMain→ Platform.kt

Once we have the Network client setup, we can configure our content negotiation to parse JSON responses, then we can use it to make network requests, we can also enable logging to visualize network transactions (optional).

We can use Kotlin Coroutines to make the network call asynchronous.

org.jetbrains.kotlinx:kotlinx-coroutines-core dependency is needed (commonMain sourceSet) in order to use Coroutines inside shared code.

How to specify a request URL?

The Ktor client allows you to configure a request URL in the following ways:
a. Pass the entire URL as String

b. Configure URL components separately

How to add query parameters to a request?

To add query string parameters, use the URLBuilder.parameters property:

How to add Headers to the request?

The headers function allows you to add several headers at once:

How to send an Object as a Json request Body?

With the enabled ContentNegotiation plugin, you can send a class instance within a request body as JSON. To do this, pass a class instance to the setBody function and set the content type to application/json using the contentType function:

For more : See documentation: https://ktor.io/docs/request.html#text

Network Transactions:

HTTP Methods:

We can specify http method (GET, POST, PUT, DELETE, HEAD, OPTION, or PATCH) by-supplying method property inside the request block.

For more : See documentation: https://ktor.io/docs/request.html#text

Usage:

Once we add the intended KMM library as dependency into the Android and iOS application (check : Writing Sharable Code for more details), we can consume searchForMovieWithTitle an exposed method.

How to make a Network request from Android?

In Android, suspend functions can be only called by other suspend functions or from a coroutine block. Typically data transactions calls are done via ViewModel,

iOS

Similarly in iOS ViewModel is the typical location to make network calls, the same searchForMovieWithTitle method can be used in iOS, and results can be consumed in a callback.

If you found it helpful, these are the related articles:
1. Getting the settings right: setting up for KMM
2. Sharing Code: with KMM
3. KMM: Whats on the plate

--

--