Skip to content

Commit

Permalink
Add Coroutines sample
Browse files Browse the repository at this point in the history
  • Loading branch information
Goooler committed Jan 2, 2024
1 parent 4c0db20 commit 381904f
Show file tree
Hide file tree
Showing 2 changed files with 58 additions and 1 deletion.
6 changes: 5 additions & 1 deletion samples/build.gradle
Original file line number Diff line number Diff line change
@@ -1,4 +1,7 @@
apply plugin: 'java-library'
plugins {
id 'java-library'
alias libs.plugins.kotlin.jvm
}

dependencies {
implementation projects.retrofit
Expand All @@ -10,5 +13,6 @@ dependencies {
implementation libs.mockwebserver
implementation libs.guava
implementation libs.jsoup
implementation libs.kotlinCoroutines
compileOnly libs.findBugsAnnotations
}
53 changes: 53 additions & 0 deletions samples/src/main/java/com/example/retrofit/KotlinCoroutines.kt
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")
}
}

0 comments on commit 381904f

Please sign in to comment.