Skip to content

Instantly share code, notes, and snippets.

@senamit2708
Created July 12, 2023 11:17
Show Gist options
  • Save senamit2708/550231da667f057e2033d9d2ff5a9d00 to your computer and use it in GitHub Desktop.
Save senamit2708/550231da667f057e2033d9d2ff5a9d00 to your computer and use it in GitHub Desktop.
Retrofit: Parallel network call
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
)
private val customerParallelNetworkCallViewM : CustomerParallelNetworkCallViewM by activityViewModels()
private fun customerListExampleFour() {
customerParallelNetworkCallViewM.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()
}
}
}
customerParallelNetworkCallViewM.getCustomerList()
}
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.coroutineScope
import kotlinx.coroutines.launch
import java.lang.Exception
class CustomerParallelNetworkCallViewM(application: Application) : AndroidViewModel(application) {
private val TAG = CustomerParallelNetworkCallViewM::class.simpleName
private val repository: CustomerRepository by lazy {
CustomerRepository(application)
}
public val uiState = MutableLiveData<UiState<List<Customer>>>()
fun getCustomerList() {
viewModelScope.launch {
uiState.postValue(UiState.loading)
try {
//coroutine scope is needed, else in case of any network error, it will crash
coroutineScope {
val customerPageOneDeferred =
async { repository.getCustomerList(currentPage = 1) }
val customerPageTwoDeferred =
async { repository.getCustomerList(currentPage = 2) }
val customerPageOne = customerPageOneDeferred.await()
val customerPageTwo = customerPageTwoDeferred.await()
val customerList = mutableListOf<Customer>()
customerPageOne?.let {
customerList.addAll(it)
}
customerPageTwo?.let {
customerList.addAll(it)
}
uiState.postValue(UiState.Success(customerList))
}
} catch (e: Exception) {
uiState.postValue(UiState.Error("something went wrong ${e.localizedMessage}"))
}
}
}
}
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, 12)
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