Skip to content

Instantly share code, notes, and snippets.

@senamit2708
Last active July 12, 2023 12:30
Show Gist options
  • Save senamit2708/582b408223baaab5f83d7855c1d09e47 to your computer and use it in GitHub Desktop.
Save senamit2708/582b408223baaab5f83d7855c1d09e47 to your computer and use it in GitHub Desktop.
Retrofit with IgnoreError and continue with coroutine
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.entity
import androidx.room.Entity
import androidx.room.PrimaryKey
import com.google.gson.annotations.SerializedName
data class Root(
@SerializedName("page") var page: Int? = null,
@SerializedName("per_page") var perPage: Int? = null,
@SerializedName("total") var total: Int? = null,
@SerializedName("total_pages") var totalPages: Int? = null,
@SerializedName("data") var data: ArrayList<Customer> = arrayListOf(),
@SerializedName("support") var support: Support? = Support()
)
@Entity(tableName = "customer")
data class Customer(
@SerializedName("id") @PrimaryKey var id: Int,
@SerializedName("email") var email: String? = null,
@SerializedName("first_name") var firstName: String? = null,
@SerializedName("last_name") var lastName: String? = null,
@SerializedName("avatar") var avatar: String? = null
)
data class Support(
@SerializedName("url") var url: String? = null,
@SerializedName("text") var text: String? = null
)
package com.example.coroutinelearning.viewModels
import android.app.Application
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.example.coroutinelearning.entity.Customer
import com.example.coroutinelearning.repositories.CustomerRepository
import com.example.coroutinelearning.sealed.UiState
import kotlinx.coroutines.async
import kotlinx.coroutines.launch
import kotlinx.coroutines.supervisorScope
import java.lang.Exception
class CustomerIgnoreErrorAndContinoueViewM(application: Application) :
AndroidViewModel(application) {
private val TAG = CustomerIgnoreErrorAndContinoueViewM::class.simpleName
private val repository: CustomerRepository by lazy {
CustomerRepository(application)
}
val uiState = MutableLiveData<UiState<List<Customer>>>()
fun getCustomerList() {
viewModelScope.launch {
uiState.postValue(UiState.loading)
supervisorScope {
val customerPageOneDeferred = async { repository.getCustomerList(currentPage = 1) }
val customerPageTwoDeferred = async { repository.getCustomerList(currentPage = 2) }
val customerPageOne = try {
customerPageOneDeferred.await()
} catch (e: Exception) {
emptyList()
}
val customerPageTwo = try {
customerPageTwoDeferred.await()
} catch (e: Exception) {
emptyList()
}
val customerList = mutableListOf<Customer>()
customerPageOne?.let {
customerList.addAll(it)
}
customerPageTwo?.let {
customerList.addAll(it)
}
uiState.postValue(UiState.Success(customerList))
}
}
}
}
private val customerIgnoreErrorAndContinoueViewM: CustomerIgnoreErrorAndContinoueViewM by activityViewModels()
private fun customerListExampleFive() {
customerIgnoreErrorAndContinoueViewM.uiState.observe(viewLifecycleOwner) {
when (it) {
is UiState.Success -> {
binding.progressBar.visibility = View.GONE
binding.userRecyclerView.visibility = View.VISIBLE
mCustomerListAdapter.setCustomerList(it.data)
}
is UiState.loading -> {
binding.progressBar.visibility = View.VISIBLE
binding.userRecyclerView.visibility = View.GONE
}
is UiState.Error -> {
binding.progressBar.visibility = View.GONE
binding.userRecyclerView.visibility = View.GONE
Toast.makeText(requireContext(), it.message, Toast.LENGTH_SHORT).show()
}
}
}
customerIgnoreErrorAndContinoueViewM.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 getCustomerList(currentPage: Int = 1): List<Customer>? {
val result = RetrofitHelper.getServices().getAllUser(currentPage, 6)
val customerData = result.body()?.data
saveCustomerDataToDB(customerData)
return customerData
}
}
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)
}
}
package com.example.coroutinelearning.sealed
sealed interface UiState<out T> {
data class Success<T>(val data: T) : UiState<T>
data class Error(val message: String) : UiState<Nothing>
object loading : UiState<Nothing>
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment