-
Notifications
You must be signed in to change notification settings - Fork 7.3k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
2 changed files
with
58 additions
and
1 deletion.
There are no files selected for viewing
This file contains 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
53 changes: 53 additions & 0 deletions
53
samples/src/main/java/com/example/retrofit/KotlinCoroutines.kt
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,53 @@ | ||
package com.example.retrofit | ||
|
||
import retrofit2.ResultCallAdapterFactory | ||
import retrofit2.Retrofit | ||
import retrofit2.converter.gson.GsonConverterFactory | ||
import retrofit2.create | ||
import retrofit2.http.GET | ||
import retrofit2.http.Path | ||
|
||
data class Contributor(val login: String, val contributions: Int) | ||
|
||
interface GitHub { | ||
@GET("/repos/{owner}/{repo}/contributors") | ||
suspend fun getContributors( | ||
@Path("owner") owner: String, | ||
@Path("repo") repo: String, | ||
): List<Contributor> | ||
|
||
@GET("/repos/{owner}/{repo}/contributors") | ||
suspend fun getContributorsWithResult( | ||
@Path("owner") owner: String, | ||
@Path("repo") repo: String, | ||
): Result<List<Contributor>> | ||
} | ||
|
||
suspend fun main() { | ||
val retrofit = Retrofit.Builder() | ||
.baseUrl("https://api.github.com") | ||
.addCallAdapterFactory(ResultCallAdapterFactory.create()) | ||
.addConverterFactory(GsonConverterFactory.create()) | ||
.build() | ||
val github: GitHub = retrofit.create() | ||
|
||
println("Request without Result using") | ||
try { | ||
github.getContributors("square", "retrofit").forEach { contributor -> | ||
println(contributor) | ||
} | ||
} catch (e: Exception) { | ||
println("An error occurred when not using Result: $e") | ||
} | ||
|
||
println("Request with Result using") | ||
github.getContributorsWithResult("square", "retrofit") | ||
.onSuccess { | ||
it.forEach { contributor -> | ||
println(contributor) | ||
} | ||
} | ||
.onFailure { | ||
println("An error occurred when using Result: $it") | ||
} | ||
} |