feat: add ClusterViewModel for recommendation feature
This commit introduces `ClusterViewModel` to manage the state and logic for fetching growth recipe recommendations.
Key functionalities:
- Manages a `StateFlow` named `_state` to represent the current state of the recommendation request (Idle, Loading, Success, Error).
- Provides a public `state` flow for observing changes in the recommendation request.
- Implements a `getRecommendation()` function that:
- Sets the state to `Loading`.
- Calls the `getRecommendation()` method of the `ClusteringRepository`.
- If successful and data is present, updates the state to `Success` with the last item from the response.
- If the response is empty, updates the state to `Error` with a "Data tidak ditemukan" message.
- Catches exceptions, maps them to user-friendly error messages, and updates the state to `Error`.
- Logs detailed error messages if fetching data fails.
This commit is contained in:
parent
e274873e43
commit
94b655481c
|
|
@ -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<ClusteringResponse>>(ResultState.Idle)
|
||||||
|
val state: StateFlow<ResultState<ClusteringResponse>> = _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}")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
Loading…
Reference in New Issue
Block a user