retrofit icon indicating copy to clipboard operation
retrofit copied to clipboard

Add support for Kotlin's Result

Open GSala opened this issue 4 years ago • 5 comments

Now that inline classes are stable in Kotlin 1.5.0, it would be nice to have API endpoints return Result to wrap the outcome (success/failure) of a retrofit call, instead of returning a value or throwing an exception.

For example:

@GET("me")
suspend fun getUser(): Result<User>

GSala avatar May 10 '21 12:05 GSala

I doubt if Retrofit should support kotlin Result at this moment, because returning kotlin Result from functions is not the default behavior.

Anyway, this call adapter will work for your use case. note: That call adapter will work for suspend fun foo() : Result<Foo> , but won't work for fun foo(): Result<Foo> in some reasons.

kobito-kaba avatar May 27 '21 04:05 kobito-kaba

Initially I thought that might be a good addition, but I guess you can always use runCatching if you want the type wrapped in Result

val user: Result<User> = runCatching {
    api.getUser()
 }

tejas-n avatar Jun 26 '21 23:06 tejas-n

val user: Result\u003CUser> = runCatching {\n api.getUser()\n }

youarenot667543 avatar Dec 03 '21 22:12 youarenot667543

You can try my solution - https://github.com/agamula90/RetrofitKx, hosted on mavenCentral, based on retrofit + moshi + ksp if you are are looking for better kotlin api

agamula90 avatar Feb 27 '23 20:02 agamula90