Tuesday, June 15, 2021

【ANDROID STUDIO】 Logging Interceptor Retrofit With Kotlin Coroutines

 package com.example.myapplication


import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Toast
import androidx.lifecycle.LiveData
import androidx.lifecycle.Observer
import androidx.lifecycle.liveData
import kotlinx.android.synthetic.main.activity_main.*
import retrofit2.Response

class MainActivity : AppCompatActivity() {
private lateinit var retService: AlbumService
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
retService = RetrofitInstance
.getRetrofitInstance()
.create(AlbumService::class.java)


getRequestWithQueryParameters()
//getRequestWithPathParameters()





}
private fun getRequestWithQueryParameters(){
val responseLiveData: LiveData<Response<Albums>> = liveData {
//val response = retService.getAlbums()
var response = retService.getSortedAlbums(3)

emit(response)
}
responseLiveData.observe(this, Observer {
val albumsList = it.body()?.listIterator()
if (albumsList != null) {
while (albumsList.hasNext()) {
val albumsItem = albumsList.next()
val result = " " + "Album Title : ${albumsItem.title}" + "\n" +
" " + "Album id : ${albumsItem.id}" + "\n" +
" " + "User id : ${albumsItem.userId}" + "\n\n\n"
text_view.append(result)
}
}
})
}
private fun getRequestWithPathParameters(){

// path parameter example
val pathResponse : LiveData<Response<AlbumsItem>> = liveData {
val response = retService.getAlbum(3)
emit(response)

}




pathResponse.observe(this, Observer {
val title = it.body()?.title
Toast.makeText(applicationContext, title, Toast.LENGTH_LONG).show()
})
}


}
package com.example.myapplication

import com.google.gson.GsonBuilder
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory

class RetrofitInstance {
companion object {
val BASE_URL = "https://jsonplaceholder.typicode.com/"
val interceptor = HttpLoggingInterceptor().apply {
this.level = HttpLoggingInterceptor.Level.BODY
}
val client = OkHttpClient.Builder().apply {
this.addInterceptor(interceptor)
}.build()

fun getRetrofitInstance(): Retrofit {
return Retrofit.Builder()
.baseUrl(BASE_URL)
.client(client)
.addConverterFactory(GsonConverterFactory.create(GsonBuilder().create()))
.build()
}

}

}

No comments:

Post a Comment