diff --git a/agrilinkvocpro/growth_recipe_feature/src/main/java/com/syaroful/agrilinkvocpro/growth_recipe_feature/presentation/recomendation/ClusterViewModel.kt b/agrilinkvocpro/growth_recipe_feature/src/main/java/com/syaroful/agrilinkvocpro/growth_recipe_feature/presentation/recomendation/ClusterViewModel.kt new file mode 100644 index 0000000..60bf5eb --- /dev/null +++ b/agrilinkvocpro/growth_recipe_feature/src/main/java/com/syaroful/agrilinkvocpro/growth_recipe_feature/presentation/recomendation/ClusterViewModel.kt @@ -0,0 +1,42 @@ +package com.syaroful.agrilinkvocpro.growth_recipe_feature.presentation.recomendation + +import android.util.Log +import androidx.lifecycle.ViewModel +import androidx.lifecycle.viewModelScope +import com.syaroful.agrilinkvocpro.core.utils.ResultState +import com.syaroful.agrilinkvocpro.core.utils.extention.mapToUserFriendlyError +import com.syaroful.agrilinkvocpro.growth_recipe_feature.data.model.ClusteringResponse +import com.syaroful.agrilinkvocpro.growth_recipe_feature.data.repository.ClusteringRepository +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.asStateFlow +import kotlinx.coroutines.launch + +private const val TAG = "ClusterViewModel" + +class ClusterViewModel(private val repository: ClusteringRepository) : ViewModel() { + + private val _state = + MutableStateFlow>(ResultState.Idle) + val state: StateFlow> = _state.asStateFlow() + + fun getRecommendation( + ) { + _state.value = ResultState.Loading + viewModelScope.launch { + try { + val response = repository.getRecommendation() + if (response.isNotEmpty()) { + val data = response.last() + _state.value = ResultState.Success(data) + } else { + _state.value = ResultState.Error("Data tidak ditemukan") + } + } catch (e: Exception) { + val errorMessage = mapToUserFriendlyError(e) + _state.value = ResultState.Error(errorMessage) + Log.d(TAG, "Failed to fetch data: ${e.message}") + } + } + } +} \ No newline at end of file