MindorksOpenSource / Retrofit-Kotlin-Coroutines-Example

An example project to demonstrate how to use Retrofit with Kotlin Coroutines in Android
279 stars 82 forks source link

Missing Generic Response Code #2

Open L1f12bscs2109 opened 4 years ago

L1f12bscs2109 commented 4 years ago

How can we check status code of response? The code is very beautifully written but i need to know how to get the response code because in interface you are returning List not Response so if you want to check mainRespository.getUsers().code you can not do it. I need to check the response code whether it is HTTP_200 , HTTP_UNAUTHORIZED so on. Help will be appreciated, thanks in advance :)

c99rahul commented 3 years ago

It can be easily doable with the help of HttpLoggingInterceptor. Here is a quick workaround for the RetrofitBuilder.kt:

object RetrofitBuilder {

   // Prepare the interceptor
    var intercepter = HttpLoggingInterceptor().apply {
        this.level = HttpLoggingInterceptor.Level.BODY
    }

   // Prepare the client
    private val client = OkHttpClient.Builder().apply {
        this.addInterceptor(intercepter)
    }.build()

    private fun getRetrofit(): Retrofit {
        return Retrofit.Builder()
            .baseUrl(Config.BASE_URL)
            .client(client) // <-- Hook the client right here
            .addConverterFactory(GsonConverterFactory.create())
            .build() //Doesn't require the adapter
    }

    val apiService: ApiService = getRetrofit().create(ApiService::class.java)
}

Filter the Logcat to see logs of OkhttpClient.