From 292ffe76763cd406f6aa285bf9bdf1c50f59cef5 Mon Sep 17 00:00:00 2001 From: ibado Date: Sun, 22 Nov 2020 14:53:35 -0300 Subject: [PATCH] Add kotlin coroutines sample --- samples/build.gradle | 2 ++ .../retrofit/KotlinCoroutinesSample.kt | 33 +++++++++++++++++++ 2 files changed, 35 insertions(+) create mode 100644 samples/src/main/java/com/example/retrofit/KotlinCoroutinesSample.kt diff --git a/samples/build.gradle b/samples/build.gradle index 36f2ddb2ae..463f37feb4 100644 --- a/samples/build.gradle +++ b/samples/build.gradle @@ -1,4 +1,5 @@ apply plugin: 'java-library' +apply plugin: 'org.jetbrains.kotlin.jvm' dependencies { implementation project(':retrofit') @@ -10,5 +11,6 @@ dependencies { implementation deps.mockwebserver implementation deps.guava implementation deps.jsoup + implementation deps.kotlinCoroutines compileOnly deps.findBugsAnnotations } diff --git a/samples/src/main/java/com/example/retrofit/KotlinCoroutinesSample.kt b/samples/src/main/java/com/example/retrofit/KotlinCoroutinesSample.kt new file mode 100644 index 0000000000..354529da7c --- /dev/null +++ b/samples/src/main/java/com/example/retrofit/KotlinCoroutinesSample.kt @@ -0,0 +1,33 @@ +package com.example.retrofit + +import kotlinx.coroutines.runBlocking +import retrofit2.Retrofit +import retrofit2.converter.gson.GsonConverterFactory +import retrofit2.http.GET +import retrofit2.http.Path + +class Contributor(val login: String, val contributions: Int) + +interface GitHub { + @GET("/repos/{owner}/{repo}/contributors") + suspend fun contributors(@Path("owner") owner: String?, @Path("repo") repo: String?): List +} + +fun main() { + // Create a very simple REST adapter which points the GitHub API. + val retrofit = Retrofit.Builder() + .baseUrl("https://api.github.com") + .addConverterFactory(GsonConverterFactory.create()) + .build() + + // Create an instance of our GitHub API interface. + val github = retrofit.create(GitHub::class.java) + + runBlocking { + // Fetch and print a list of the contributors to the library. + val contributors = github.contributors("square", "retrofit") + contributors.forEach { contributor -> + println(contributor.login + " (" + contributor.contributions + ")") + } + } +} \ No newline at end of file