I am trying, following the principles of UDF, to display/change the state of the screen through the State class. I get data from the database(Room) -> repository -> useCase in the ViewModel and try to map this data there, but it doesn't work. Tell me what's wrong. I tried to make a test variable categoryTest and subscribe to it - everything works, the data comes to the fragment and the list is filled in. From this I conclude that the problem lies somewhere inside MediatorLiveData().apply, but maybe somewhere else.
` class MenuViewModel @Inject constructor( private val loadCategoryUseCase: LoadCategoryUseCase, private val getListCategoryUseCase: GetListCategoryUseCase ) : ViewModel() {
private val _categories = MutableLiveData<StateMenuFragment>()
val categories: LiveData<StateMenuFragment>
get() = _categories
val categoryTest = getListCategoryUseCase() // Test variable
init {
viewModelScope.launch {
loadCategoryUseCase()
}
getCategories()
}
private fun getCategories() {
_categories.value = StateMenuFragment(loading = true)
viewModelScope.launch {
try {
val result = getListCategoryUseCase()
MediatorLiveData<StateMenuFragment>().apply {
addSource(result) { categoryList ->
val updatedState = _categories.value?.copy(result = categoryList )
?: StateMenuFragment(result = categoryList )
_categories.value = updatedState
}
}
} catch (e: IOException) {
if (_categories.value == StateMenuFragment(result = emptyList())) {
_categories.value = StateMenuFragment(
error = ErrorMessage(isError = true, errorMessage = "error message")
)
}
}
}
}
}
I subscribe to them in the fragment. But the list doesn't come
class MenuFragment : Fragment() {
private fun updateState() {
viewModel.categories.observe(viewLifecycleOwner) {
binding.progressBar.visibility = View.GONE
if (it.loading) {
binding.progressBar.visibility = View.VISIBLE
}
if (it.error.isError) {
Toast.makeText(requireContext(), it.error.errorMessage, Toast.LENGTH_SHORT). apply {
setGravity(Gravity.CENTER, 0, 0)
}.show()
}
menuAdapter.submitList(it.result)
}
// I subscribe directly, I pass the State class - the data is coming
viewModel.categoryTest.observe(viewLifecycleOwner) {
menuAdapter.submitList(it)
}
}
}
data class StateMenuFragment(
var result: List<Category> = emptyList(),
val loading: Boolean = false,
val error: ErrorMessage = ErrorMessage()
)
data class ErrorMessage(
val isError: Boolean = false,
val errorMessage: String = ""
)
data class Category (
val id: Int,
val title: String,
val imageUrl: String
)`