Skip to content

Commit

Permalink
favorite logic is added to viewModel
Browse files Browse the repository at this point in the history
  • Loading branch information
masooddalman committed Aug 26, 2023
1 parent 9e5426e commit 290386f
Showing 1 changed file with 37 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@ import android.content.Context
import android.util.Log
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import com.liliputdev.mvvmexample.repository.database.FavDatabase
import com.liliputdev.mvvmexample.repository.database.dataModel.FavProduct
import com.liliputdev.mvvmexample.repository.retrofit.RetrofitService
import com.liliputdev.mvvmexample.repository.retrofit.WebRepository
import com.liliputdev.mvvmexample.repository.retrofit.apiModel.APIModelAllProduct
Expand All @@ -19,15 +21,20 @@ class MainActivityViewModel(val context: Context) : ViewModel() {
val _retrofit = RetrofitService.getInstance()
private var repository: WebRepository = WebRepository(_retrofit)
val listData = MutableLiveData<ArrayList<APIModelAllProductElement>>()
val favDb=FavDatabase.getInstance(context)

fun getAllProduct() {
val favProduct=getAllFavProduct()
val response = repository.getAllProduct()
response.enqueue(object : Callback<APIModelAllProduct> {
override fun onResponse(
call: Call<APIModelAllProduct>,
response: Response<APIModelAllProduct>
) {
Log.v("masood", "all product size: ${response.body()?.size}")
response.body()?.forEach {
it.isfaved=isThisProductFaved(it.id,favProduct)
}
listData.postValue(response.body())
response.body()?.forEach {
Log.v("masood", "item : ${it.title} - category:${it.category}")
Expand Down Expand Up @@ -77,4 +84,34 @@ class MainActivityViewModel(val context: Context) : ViewModel() {
}
return result!!
}

fun getAllFavProduct(): List<FavProduct> {
return favDb.favDao().getFavList()
}

private fun isThisProductFaved(id:Int,favProducts:List<FavProduct>):Boolean
{
var result=false
favProducts.forEach {
if(it.id==id)
{
result=it.isFaved
}
}
return result
}

fun manageFav(model: APIModelAllProductElement)
{
if(model.isfaved)
{
//remove
favDb.favDao().delete(FavProduct(model.id,true))
}
else
{
//add
favDb.favDao().addNewFav(FavProduct(model.id,true))
}
}
}

0 comments on commit 290386f

Please sign in to comment.