Is it possible to define something similar to Retr...
# ktor
m
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
Can you please share an example to illustrate the question?
m
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
I don't think it's possible to do via the plugin. You'd need to write wrappers for each request method.
m
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
runCatching?
m
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
.