https://kotlinlang.org logo
#ktor
Title
# ktor
m

Matija Sokol

11/22/2023, 3:58 PM
Is it possible to define something similar to Retrofit CallAdapter.Factory to define custom return types using Ktor client on Android? I want to define my return type using Arrow's
Either<Left, Right>
a

Aleksei Tirman [JB]

11/22/2023, 5:40 PM
Can you please share an example to illustrate the question?
m

Matija Sokol

11/22/2023, 6:05 PM
Sure. For simplicity lets define our model like this (probably same approach will be also with
Either
):
Copy code
sealed class Result<out T> {
  data class Success<out T>(val data: T) : Result<T>()
  data class Error(val error: ErrorEntity) : Result<Nothing>()
}
And what I want is to return
Result
type when calling
HttpClient
methods:
Copy code
suspend fun fetchData(): Result<String> = httpClient.get(url).body()
What I found is that maybe I can do this by creating plugin but I'm not sure if I'm on the right track:
Copy code
val ConverterPlugin = createClientPlugin("ConverterPlugin", ::ConverterPluginConfig) {
  transformResponseBody { response, content, requestedType ->
  }
}
a

Aleksei Tirman [JB]

11/22/2023, 6:07 PM
I don't think it's possible to do via the plugin. You'd need to write wrappers for each request method.
m

Matija Sokol

11/22/2023, 8:01 PM
Something like this?
Copy code
suspend fun fetchData(): Result<String> = try {
  Result.success(httpClient.get(url).body())
} catch (t: Throwable) {
  Result.failure(t)
}
👌 1
m

MV

11/23/2023, 6:34 PM
runCatching?
m

Matija Sokol

11/23/2023, 6:52 PM
It would also works with
runCatching
. Actually, I would prefer
runCatching
if
Kotlin Result
type is used, but for custom models I would go with
try-catch
.