我是使用 MVVM 和 Kotlin 的新手。我决定在一个新项目中使用它们,我不知道有什么问题。我正在使用Hilt
MVVM
等ViewModel
希望你能帮助我
当有人按下fab_add_check
按钮时,这是从数据库请求数据的片段。我打开一个新活动以将新行插入数据库,我能够检查数据库。所以我知道插入有效,但是为什么 ui 没有更新?
@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))
}