Skip to content

Instantly share code, notes, and snippets.

@senamit2708
Created July 11, 2023 14:27
Show Gist options
  • Save senamit2708/16ac72f122772b74b42fecf3d38b17ee to your computer and use it in GitHub Desktop.
Save senamit2708/16ac72f122772b74b42fecf3d38b17ee to your computer and use it in GitHub Desktop.
Retrofit with coroutine -> Advance One
package com.example.coroutinelearning.retrofits
import com.example.coroutinelearning.entity.Root
import retrofit2.Response
import retrofit2.http.GET
import retrofit2.http.Query
interface ApiInterface {
@GET("/api/users")
suspend fun getAllUser(
@Query("page") currentPage: Int, @Query("per_page") pageSize: Int
): Response<Root>
}
package com.example.coroutinelearning.fragments
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.LinearLayoutManager
import com.example.coroutinelearning.adapter.CustomerListAdapter
import com.example.coroutinelearning.databinding.CustomerListBinding
import com.example.coroutinelearning.viewModels.CustomerTwoViewModel
import com.example.coroutinelearning.viewModels.CustomerViewModel
class CustomerListFragment : Fragment() {
private val TAG = CustomerListFragment::class.simpleName
private lateinit var binding: CustomerListBinding
private val mLayoutManager: LinearLayoutManager by lazy {
LinearLayoutManager(requireContext())
}
private val mCustomerListAdapter: CustomerListAdapter by lazy {
CustomerListAdapter(requireContext())
}
private val customerTwoViewModel: CustomerTwoViewModel by lazy {
ViewModelProvider(requireActivity()).get(CustomerTwoViewModel::class.java)
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
}
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?
): View? {
binding = CustomerListBinding.inflate(inflater, container, false)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
binding.userRecyclerView.adapter = mCustomerListAdapter
binding.userRecyclerView.layoutManager = mLayoutManager
customerListExampleTwo()
}
private fun customerListExampleTwo() {
customerTwoViewModel.customerList.observe(viewLifecycleOwner) { customerList ->
customerList?.let {
mCustomerListAdapter.setCustomerList(customerList)
}
}
customerTwoViewModel.errorMessage.observe(viewLifecycleOwner) {
Toast.makeText(requireContext(), it, Toast.LENGTH_SHORT).show()
}
customerTwoViewModel.loading.observe(viewLifecycleOwner) {
if (it) {
binding.progressBar.visibility = View.GONE
} else {
binding.progressBar.visibility = View.VISIBLE
}
}
customerTwoViewModel.getCustomerList()
}
}
package com.example.coroutinelearning.repositories
import android.app.Application
import android.util.Log
import com.example.coroutinelearning.database.AppDatabase
import com.example.coroutinelearning.database.CustomerDao
import com.example.coroutinelearning.entity.Customer
import com.example.coroutinelearning.entity.Root
import com.example.coroutinelearning.retrofits.RetrofitHelper
import retrofit2.Response
class CustomerRepository(application: Application) {
private val TAG = CustomerRepository::class.simpleName
private val appDatabase: AppDatabase
private val customerDao: CustomerDao
init {
appDatabase = AppDatabase.getDatabase(application)
customerDao = appDatabase.getCustomerDao()
}
suspend fun getCustomerListExampleTwo(): Response<Root> {
return RetrofitHelper.getServices().getAllUser(1, 12)
}
}
package com.example.coroutinelearning.viewModels
import android.app.Application
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.MutableLiveData
import com.example.coroutinelearning.entity.Customer
import com.example.coroutinelearning.repositories.CustomerRepository
import kotlinx.coroutines.CoroutineExceptionHandler
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
class CustomerTwoViewModel(application: Application) : AndroidViewModel(application) {
private val TAG = CustomerTwoViewModel::class.simpleName
private val repsotiory: CustomerRepository
val errorMessage = MutableLiveData<String>()
val customerList = MutableLiveData<List<Customer>?>()
private var job: Job? = null
val loading = MutableLiveData<Boolean>()
private val exceptionHandler: CoroutineExceptionHandler
init {
repsotiory = CustomerRepository(application)
exceptionHandler = CoroutineExceptionHandler { _, throwable ->
onError("Exception Handled: ${throwable.localizedMessage}")
}
}
fun getCustomerList() {
job = CoroutineScope(Dispatchers.IO + exceptionHandler).launch {
val response = repsotiory.getCustomerListExampleTwo()
withContext(Dispatchers.Main) {
if (response.isSuccessful) {
val data = response.body()?.data
customerList.postValue(data)
loading.value = false
} else {
onError("Error ${response.message()}")
}
}
}
}
private fun onError(message: String) {
errorMessage.value = message
loading.value = false
}
override fun onCleared() {
super.onCleared()
job?.cancel()
}
}
package com.example.coroutinelearning.retrofits
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
object RetrofitHelper{
private const val baseUrl = "https://reqres.in"
private val mHttpLoginInterceptor = HttpLoggingInterceptor()
.setLevel(HttpLoggingInterceptor.Level.BODY)
private val mOkHttpClient = OkHttpClient.Builder()
.addInterceptor(mHttpLoginInterceptor)
.build()
fun getInstance() : Retrofit {
return Retrofit.Builder()
.baseUrl(baseUrl)
.addConverterFactory(GsonConverterFactory.create())
.client(mOkHttpClient)
.build()
}
fun getServices() : ApiInterface{
return getInstance().create(ApiInterface::class.java)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment