Hi, anyone using Ktor for android to replace Retro...
# android
r
Hi, anyone using Ktor for android to replace Retrofit? It looks simple like khttp library. Any guide is appreciated
f
yes it is as simple as
Copy code
suspend fun search(query: String, page: Int): List<Repo> {
    val result: Result = httpClient.get("<https://api.github.com/search/repositories>") {
        url {
            parameter("q", query)
            parameter("page", page)
        }
    }
    return result.repos
}
where
Copy code
val json: Json = Json {
    isLenient = true
    ignoreUnknownKeys = true
}

val httpClient: HttpClient = HttpClient(engineFactory = CIO) {
    install(feature = JsonFeature) {
        serializer = KotlinxSerializer(json = json)
    }
    install(feature = Logging) {
        logger = Logger.SIMPLE
        level = LogLevel.BODY
    }
}
Example: here
👍 1
r
Thank you. I'll check it. I need to generalize this solution for every request.
r
Why do you want to replace Retrofit?
K 3
r
Because its not well fitting with my use case.
z
what usecase exists where Retrofit is not fitting?? 🤔
f
Multiplatform maybe
r
Not multi-platform, but I need to do some preparation before sending request and lots of criteria. And Interceptor for retrofit is somehow not working properly. Might be my implementation issue. But wanted to look at ktor
r
OK, the interceptors are sometimes getting too complex. We use retrofit with Moshi, and it works well now; after a interceptor cleanup. I prefer Ktor for the backend.
r
Yes retrofit and moshi works correctly with model class. But my response is very large so I prefer to just use response body instead of model class. And some interceptor is not working arbitrarily. So I was looking for alternative. I'll try more with retrofit if it works.
r
Cool - it will be interesting to hear your conclusions.
j
I think the syntax of ktor is so dead easy that there is not really a big use for retrofit, especially if you have a bunch of extension functions. So as retrofit is basically used to shape your API usage and hides the code in generated code, using kotlin you can also have simple and beautiful code and you can hide the code in for example extension functions. Also you do not need annotation processors so you have a faster build. Last but not least, you can still use OKHTTP's logging and interceptors so you will have beautiful logs and can still use interceptions.
But having said that, I would only use ktor in a new project. I wouldn't see the need to migrate a full working Android project, if it is not multiplatform and will never be multiplatform. Retrofit is in any case not bad 🙂
👍 2
262 Views