How to use common engine in Ktor

609 views Asked by At

Hey I am trying to implement KMM in my existing Android and iOS project. I following this kmm-config. I want to implement interceptor and authentication. In doc example both Android and iOS ktor engine is separated in androidMain and iosMain respectively. So I want to write interceptor in both platform like separate or just use in commonMain. Is there is a way to use common engine in both platform? Thanks

1

There are 1 answers

2
Praveen On

HTTP Engines are platform-dependent, so you have to use different engines for each platform, which you can define in each platform's shared package.

Create a variable with expect keyword, inside commonMain

expect val httpEngine: HttpEngine

Provide an actual declaration inside each platform Main package

Android

actual val httpEngine = Android.create {
    //configure intercepter here
}

IOS

acutal val httpEngine = Ios.create {
    //configure intercepter here
}

You can use this httpEngine inside commonMain package to create an HttpClient and configure authentication

fun createHttpClient(httpEngine: HttpClientEngine) =
    HttpClient(httpEngine) {
        install(Auth) {
            //configure authentication
        }
    }
    

You can read more about ktor authentication here