-
-
Save morristech/84b234309579947fa55edd0d39cae315 to your computer and use it in GitHub Desktop.
Example of usage kotlin-coroutines-retrofit with awaitResponse()
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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