I am new using MVVM and Kotlin. I decided to use them in a new project, I do not know what is wrong.
I am using Hilt
MVVM
and ViewModel
etc. hopefully you can help me
This is the Fragment who request the data from the db, when somebody presses the fab_add_check
button.
I open a new activity to insert a new row into the db, I able to check the db.
so I know insert works, however why the ui is not updated?
@ExperimentalCoroutinesApi
@AndroidEntryPoint
class CheckFragment : BaseFragment() {
private lateinit var checkAdapter: CheckAdapter
private val checkViewModel: CheckViewModel by viewModels()
companion object {
private const val ARG_FLAG = "ARG_FLAG"
private const val ARG_CHECK_STATUS = "ARG_CHECK_STATUS"
@JvmStatic
fun newInstance(isAllFrag: Boolean, checkStatus: CheckStatus) = CheckFragment().apply {
arguments = Bundle().apply {
putBoolean(ARG_FLAG, isAllFrag)
putString(ARG_CHECK_STATUS, checkStatus.name)
}
}
}
override fun setLayout() = R.layout.fragment_check
override fun initFragment(view: View) {
if (requireArguments().getBoolean(ARG_FLAG)) view.fab_add_check.show()
else view.fab_add_check.hide()
view.check_rv?.layoutManager = LinearLayoutManager(requireContext())
view.fab_add_check.setOnClickListener {
startActivity(Intent(context, ScanCheckActivity::class.java))
}
getChecks(requireArguments().getString(ARG_CHECK_STATUS))
}
//Get check from the db
private fun getChecks(checkStatus: String?) {
checkViewModel.setCheckStatus(checkStatus)
checkViewModel.checks.observe(this, Observer {
checkAdapter = CheckAdapter(it, requireContext())
view?.check_rv?.adapter = checkAdapter
})
}
}
//Here the ViewModel
@ExperimentalCoroutinesApi
class CheckViewModel
@ViewModelInject constructor(private val checkRepository: CheckRepository) : ViewModel(){
private val _checks = MutableLiveData<List<Check>>()
val checks: LiveData<List<Check>>
get() = _checks
fun saveCheck(check: Check) {
viewModelScope.launch {
checkRepository.insertCheck(check)
}
}
fun setCheckStatus(checkStatus: String?) {
viewModelScope.launch {
_checks.postValue(checkRepository.getChecksByStatus(checkStatus!!))
}
}
}
//Repository
class CheckRepository @Inject constructor(
private val db: AppDataBase,
private val checkEntityMapper: CheckEntityMapper
) {
//From db
fun getChecksByStatus(checkStatus: String) =
if (checkStatus == CheckStatus.UNKNOWN.name) checkEntityMapper.mapFormEntityList(db.checkDao().getChecks())
else checkEntityMapper.mapFormEntityList(db.checkDao().getChecksByStatus(checkStatus))
fun insertCheck(check: Check) = db.checkDao().insertCheck(checkEntityMapper.mapToEntity(check))
}