Retrofit with Kotlin Coroutine in Android - GeeksforGeeks

10 Nov, 2021
The Kotlin team defines coroutines as “lightweight threads”. They are sort of tasks that the actual threads can execute. Coroutines were added to Kotlin in version 1.3 and are based on established concepts from other languages. Kotlin coroutines introduce a new style of concurrency that can be used on Android to simplify async code. In this article, we will learn about retrofit using Kotlin coroutine. So we will be using Retrofit for network requests. Retrofit is a very popular library used for working APIs and very commonly used as well. We will learn it by making a simple app using an API to get some data using Retrofit.
Step 1: Create a New Project
To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio.
Step 2: Add dependency 
Navigate to the Gradle Scripts > build.gradle(Module:app) and add the below dependency in the dependencies section.
// retrofit
implementation ‘com.squareup.retrofit2:retrofit:2.9.0’
// GSON
implementation ‘com.squareup.retrofit2:converter-gson:2.9.0’
// coroutine
implementation ‘org.jetbrains.kotlinx:kotlinx-coroutines-android:1.5.2’
implementation ‘org.jetbrains.kotlinx:kotlinx-coroutines-core:1.5.2’
We are using GSON to convert JSON to kotlin(Java) object. We will add these dependencies in build.gradle file inside our project.
Step 3: We will use the below API
https://quotable.io/quotes?page=1
Figure 01
So our JSON response will look like this Figure01.
Step 4: Then we will create data classes according to JSON response
In JSON response we have 2 JSON objects, So we will create 2 data class 
QuoteListResults
QuoteList
Results
Kotlin
// data class QuoteList // according to JSON responsepackage com.ayush.retrofitexample  data class QuoteList(    val count: Int,    val lastItemIndex: Int,    val page: Int,    val results: List<Result>,    val totalCount: Int,    val totalPages: Int)
2nd data class
Kotlin
package com.ayush.retrofitexample  data class Result(    val _id: String,    val author: String,    val authorSlug: String,    val content: String,    val dateAdded: String,    val dateModified: String,    val length: Int,    val tags: List<String>)
Step 5: We will create a Retrofit interface to add the endpoints of the URL (quotes in our case is the endpoint)
Kotlin
// Retrofit interfacepackage com.ayush.retrofitexample  import retrofit2.Responseimport retrofit2.http.GETimport retrofit2.http.Query  interface QuotesApi {    @GET("/quotes")    suspend fun getQuotes() : Response<QuoteList>}
Step 6: We will create a new file to get the Retrofit object
In this file, we will have a function that will return the Retrofit object.
Kotlin
package com.ayush.retrofitexample  import retrofit2.Retrofitimport retrofit2.converter.gson.GsonConverterFactory  object RetrofitHelper {      val baseUrl = "https://quotable.io/"      fun getInstance(): Retrofit {        return Retrofit.Builder().baseUrl(baseUrl)            .addConverterFactory(GsonConverterFactory.create())             // we need to add converter factory to             // convert JSON object to Java object            .build()    }}
Step 7: Now we will link the Retrofit object and Retrofit interface file in MainActivity
Kotlin
package com.ayush.retrofitexample  import androidx.appcompat.app.AppCompatActivityimport android.os.Bundleimport android.util.Logimport kotlinx.coroutines.GlobalScopeimport kotlinx.coroutines.launchimport retrofit2.create  class MainActivity : AppCompatActivity() {    override fun onCreate(savedInstanceState: Bundle?) {        super.onCreate(savedInstanceState)        setContentView(R.layout.activity_main)          val quotesApi = RetrofitHelper.getInstance().create(QuotesApi::class.java)        // launching a new coroutine        GlobalScope.launch {          val result = quotesApi.getQuotes()            if (result != null)                // Checking the results                Log.d("ayush: ", result.body().toString())        }      }}
Step 8: Add Internet permission in the manifests file
<uses-permission android:name=”android.permission.INTERNET”></uses-permission>
Results: we can check the logcat window. We can see the result in the green box.
Output:
Android
Kotlin
Android
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Resource Raw Folder in Android Studio
Flutter - Custom Bottom Navigation Bar
How to Read Data from SQLite Database in Android?
How to Post Data to API using Retrofit in Android?
How to Get Current Location in Android?
Android UI Layouts
Kotlin Array
How to Get Current Location in Android?
Kotlin Setters and Getters
Kotlin when expression