Search code examples
androidretrofitretrofit2kotlin-coroutines

How to handle 204 response in Retrofit using Kotlin Coroutines?


I'm using Retrofit 2.7.1 with Kotlin coroutines.

I have a Retrofit service defined as such:

@PUT("/users/{userId}.json")
suspend fun updateUserProfile(
        @Path("userId") userId: String,
        @Query("display_name") displayName: String) : Void

This call returns an HTTP 204 No Content response, which causes a crash in Retrofit:

kotlin.KotlinNullPointerException: Response from com.philsoft.test.api.UserApiService.updateUserProfile was null but response body type was declared as non-null
        at retrofit2.KotlinExtensions$await$2$2.onResponse(KotlinExtensions.kt:43)
        at retrofit2.OkHttpCall$1.onResponse(OkHttpCall.java:129)
        at okhttp3.RealCall$AsyncCall.execute(RealCall.java:174)
        at okhttp3.internal.NamedRunnable.run(NamedRunnable.java:32)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
        at java.lang.Thread.run(Thread.java:919)

How do I handle a 204 response in retrofit, using coroutines, without crashing?


Solution

  • According to this, use Response<Unit> in the retrofit method declaration.

    retrofit no content issue