Skip to content

Instantly share code, notes, and snippets.

@gildor
Last active June 22, 2021 19:09
Show Gist options
  • Save gildor/aa2b2f23ffbc963e3bde2f180150cc07 to your computer and use it in GitHub Desktop.
Save gildor/aa2b2f23ffbc963e3bde2f180150cc07 to your computer and use it in GitHub Desktop.
Example of usage kotlin-coroutines-retrofit with awaitResponse()
import kotlinx.coroutines.experimental.runBlocking
import retrofit2.Call
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import retrofit2.http.GET
import retrofit2.http.Path
import ru.gildor.coroutines.retrofit.awaitResponse
/**
dependencies {
compile "org.jetbrains.kotlin:kotlin-stdlib-jre8:1.1.2-2"
compile "org.jetbrains.kotlinx:kotlinx-coroutines-core:0.15"
compile "ru.gildor.coroutines:kotlin-coroutines-retrofit:0.5.0"
compile "com.squareup.retrofit2:retrofit:2.2.0"
compile "com.squareup.retrofit2:converter-gson:2.2.0"
}
*/
fun main(args: Array<String>) = runBlocking {
val resp = api.user("gildor").awaitResponse()
println(resp)
println(if (resp.isSuccessful) resp.body() else resp.errorBody())
println("Finished")
}
val api: GitHub = Retrofit.Builder()
.addConverterFactory(GsonConverterFactory.create())
.baseUrl("https://api.github.com")
.build()
.create(GitHub::class.java)
interface GitHub {
@GET("/users/{login}")
fun user(@Path("login") login: String): Call<User>
}
data class User(val login: String, val name: String)
/**
Output:
-- Before coroutine --
Response{protocol=http/1.1, code=200, message=OK, url=https://api.github.com/users/gildor}
User(login=gildor, name=Andrey Mischenko)
Finished
-- After coroutine --
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment