I have a multiplatform Android / iOS app and want ...
# ktor
l
I have a multiplatform Android / iOS app and want to use on Android OkHttp with custom DNS implementation. The Ktor
HttpClient
is declared in the shared multiplatform part. How can I inject
OkHttp
with the custom DNS into the shared part only for Android?
s
My personal choice would be to create an
expect fun createEngine(): HttpClientEngineFactory<T>
and return the OkHttp version from Android configured with your custom DSN, and the darwin version on iOS.
HttpClient(createEngine())
If you're using DI like Koin, you can alternatively also use that.
l
What is
T
in this case?
s
Ah, it's the type of the config specific to the engine used. So in my case with
Apache
.
data object Apache : HttpClientEngineFactory<ApacheEngineConfig>
. For
data object OkHttp : HttpClientEngineFactory<OkHttpConfig>
which gives you access to the
underlying
client for example. Reference: OkHttpConfig API Docs
So you can configure:
Copy code
val client: HttpClient = HttpClient(OkHttp) {
  // configure OkHttp
}
l
Ok, thank you for the suggestion!
s
I'm sorry, I made a mistake 😅 You need to share a preconfigured client engine.
Copy code
expect fun createEngine(): HttpClientEngine
Copy code
actual fun createEngine(): HttpClientEngine =
   OkHttp.create {
     // configure
   }
l
Thank you, that worked perfectly and was actually very simple, once you wrap your mind around how expect/actual work 🙂
🙌 1
kodee loving 1