gildor / kotlin-coroutines-retrofit

Kotlin Coroutines await() extension for Retrofit Call
Apache License 2.0
849 stars 64 forks source link

How to use this library ? #53

Open rahulr4 opened 5 years ago

rahulr4 commented 5 years ago

Hi, I am trying to use this library .Here is my code :-

@GET(ApiEndPoint.API_MODELS)
Call<ModelResponse> getCarModelsAsync2(@Query("itemsPerPage") String itemsPerPage);
fun getModelData() = runBlocking {
        try {
            // Wait (suspend) for response
            val result: Result<ModelResponse> = dataManager.getCarModelsAsync2("100").awaitResult()
            // Check result type
            when (result) {
                //Successful HTTP result
                is Result.Ok -> {

                }
                // Any HTTP error
                is Result.Error -> {
//                    log("HTTP error with code ${result.error.code()}", result.error)
                }
                // Exception while request invocation
                is Result.Exception -> {
//                    log("Something broken", e)
                }
            }
//            if (response) {
//                // Now we can work with response object
//                println("User ${response.body().toString()} loaded")
//            }
        } catch (e: Throwable) {
            // All other exceptions (non-http)
            e.printStackTrace()
        }
    }
public suspend fun <T : Any> Call<T>.awaitResult(): Result<T> {
    return suspendCancellableCoroutine { continuation ->
        enqueue(object : Callback<T> {
            override fun onResponse(call: Call<T>?, response: Response<T>) {
                continuation.resumeWith(runCatching {
                    if (response.isSuccessful) {
                        val body = response.body()
                        if (body == null) {
                            Result.Exception(NullPointerException("Response body is null"))
                        } else {
                            Result.Ok(body, response.raw())
                        }
                    } else {
                        Result.Error(HttpException(response), response.raw())
                    }
                })
            }

            override fun onFailure(call: Call<T>, t: Throwable) {
                // Don't bother with resuming the continuation if it is already cancelled.
                if (continuation.isCancelled) return
                continuation.resume(Result.Exception(t))
            }
        })

        registerOnCompletion(continuation)
    }
}

I can see the response in log but nowhere callback is coming. I have attached debug everywhere

gildor commented 5 years ago

Hi

but nowhere callback is coming

Not sure what you mean, your snippet doesn't print/log any result, only errors, add some result handling to Result.Ok branch:

is Result.Ok -> {
    println("My model response: ${result.value}")
}