From 381904f35de6b056f000529e87e49e9ff18bdf32 Mon Sep 17 00:00:00 2001 From: Goooler Date: Tue, 2 Jan 2024 15:54:20 +0800 Subject: [PATCH] Add Coroutines sample --- samples/build.gradle | 6 ++- .../com/example/retrofit/KotlinCoroutines.kt | 53 +++++++++++++++++++ 2 files changed, 58 insertions(+), 1 deletion(-) create mode 100644 samples/src/main/java/com/example/retrofit/KotlinCoroutines.kt diff --git a/samples/build.gradle b/samples/build.gradle index c832e73395..9a57aa4b8a 100644 --- a/samples/build.gradle +++ b/samples/build.gradle @@ -1,4 +1,7 @@ -apply plugin: 'java-library' +plugins { + id 'java-library' + alias libs.plugins.kotlin.jvm +} dependencies { implementation projects.retrofit @@ -10,5 +13,6 @@ dependencies { implementation libs.mockwebserver implementation libs.guava implementation libs.jsoup + implementation libs.kotlinCoroutines compileOnly libs.findBugsAnnotations } diff --git a/samples/src/main/java/com/example/retrofit/KotlinCoroutines.kt b/samples/src/main/java/com/example/retrofit/KotlinCoroutines.kt new file mode 100644 index 0000000000..26e7411a8f --- /dev/null +++ b/samples/src/main/java/com/example/retrofit/KotlinCoroutines.kt @@ -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 + + @GET("/repos/{owner}/{repo}/contributors") + suspend fun getContributorsWithResult( + @Path("owner") owner: String, + @Path("repo") repo: String, + ): Result> +} + +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") + } +}