Coroutines with Retrofit

Coroutines with Retrofit



Project Structure

Project 
  • build.gradle
  • MyAPI.kt
  • MyInterceptor.kt
  • Comment.kt
  • Manifest.xml
  • MainActivity.kt
  • MainActivityWithCt.kt

 retrofit without coroutines

build.gradle

dependencies {

implementation 'androidx.core:core-ktx:1.7.0'
implementation 'androidx.appcompat:appcompat:1.4.0'
implementation 'com.google.android.material:material:1.4.0'
implementation 'androidx.constraintlayout:constraintlayout:2.1.2'
testImplementation 'junit:junit:4.+'
androidTestImplementation 'androidx.test.ext:junit:1.1.3'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'

implementation("org.jetbrains.kotlinx:kotlinx-coroutines-android:1.3.9")
implementation 'com.squareup.retrofit2:retrofit:2.9.0'
implementation 'com.squareup.retrofit2:converter-gson:2.9.0'
implementation 'com.squareup.okhttp3:logging-interceptor:4.9.3'
}

MyAPI.kt
import com.rayhub.coroutinesretrofit.data.Comment
import retrofit2.Call
import retrofit2.Response
import retrofit2.http.GET

interface MyAPI {

//Coroutines
@GET("/comments")
fun getComments(): Response<List<Comment>>

//Default
@GET("/comments")
fun getCommentsCall(): Call<List<Comment>>
}

MyInterceptor.kt
import okhttp3.Interceptor
import okhttp3.Response

class MyInterceptor : Interceptor {
override fun intercept(chain: Interceptor.Chain): Response {
val request = chain.request()
.newBuilder()
.addHeader("Context-Type", "application/json")
.build()
return chain.proceed(request)
}
}

Manifest.xml


<uses-permission android:name="android.permission.INTERNET" />


Comment.kt
data class Comment(
val body: String,
val email: String,
val id: Int,
val name: String,
val postId: Int
)

MainActivity.kt

package com.rayhub.coroutinesretrofit

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import com.rayhub.coroutinesretrofit.api.MyAPI
import com.rayhub.coroutinesretrofit.api.MyInterceptor
import com.rayhub.coroutinesretrofit.data.Comment
import okhttp3.OkHttpClient
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import okhttp3.logging.HttpLoggingInterceptor


const val BASE_URL = "https://jsonplaceholder.typicode.com"

class MainActivity : AppCompatActivity() {

val TAG = "MainActivity"

override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)

val logging : HttpLoggingInterceptor = HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY)
var client = OkHttpClient.Builder().apply {
addInterceptor(MyInterceptor())
addInterceptor(logging)
}.build()

val api = Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.client(client)
.build()
.create(MyAPI::class.java)

api.getComments().enqueue(object : Callback<List<Comment>>{
override fun onFailure(call: Call<List<Comment>>, t: Throwable) {
Log.e(TAG, "ERROR: $t")
}

override fun onResponse(call: Call<List<Comment>>, response: Response<List<Comment>>) {
if(response.isSuccessful){
response.body()?.let {
for (comment in it){
Log.d(TAG, comment.toString())
}
}
}
}
})

}
}

retrofit with coroutines

MainActivityWithCt.kt


import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import com.rayhub.coroutinesretrofit.api.MyAPI
import com.rayhub.coroutinesretrofit.api.MyInterceptor
import com.rayhub.coroutinesretrofit.data.Comment
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import okhttp3.Dispatcher
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.*
import retrofit2.converter.gson.GsonConverterFactory
import kotlin.math.log

class MainActivityWithCt : AppCompatActivity() {

val BASE_URL = "https://jsonplaceholder.typicode.com"
val TAG = "MainActivity"

override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main_with_ct)

val logging : HttpLoggingInterceptor = HttpLoggingInterceptor().setLevel(
HttpLoggingInterceptor.Level.BODY)
var client = OkHttpClient.Builder().apply {
addInterceptor(MyInterceptor())
addInterceptor(logging)
}.build()

val api = Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.client(client)
.build()
.create(MyAPI::class.java)

// GlobalScope.launch(Dispatchers.IO) {
// val comments = api.getComments().await()
// for (comment in comments){
// Log.d(TAG, comment.toString())
// }
// }

GlobalScope.launch(Dispatchers.IO) {
val response = api.getComments()
if(response.isSuccessful){
for (comment in response.body()!!){
Log.d(TAG, comment.toString())
}
}
}

}
}

0 comments :

Post a Comment