0

我是使用 MVVM 和 Kotlin 的新手。我决定在一个新项目中使用它们,我不知道有什么问题。我正在使用Hilt MVVMViewModel希望你能帮助我

当有人按下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))
}
4

1 回答 1

0

您可以将传入的数据保存为 livedata 或 mutablelivedata,您可以在任何地方进行更新过程。

class NewsAdapter(
private val setOnClickListener: (NewsModel) -> Unit) : ListAdapter<NewsModel,NewsHolder>(DiffCallBack()) { override funonCreateViewHolder(parent:ViewGroup, viewType: Int): NewsHolder {

    val newsCardBinding: NewsCardBinding =
        NewsCardBinding.inflate(LayoutInflater.from(parent.context))

    return NewsHolder(newsCardBinding)

}

override fun onBindViewHolder(holder: NewsHolder, position: Int) {
    holder.bind(getItem(position), setOnClickListener)
}

class DiffCallBack : DiffUtil.ItemCallback<NewsModel>() {
    override fun areItemsTheSame(oldItem: NewsModel, newItem: NewsModel): Boolean =
        oldItem.title == newItem.title

    override fun areContentsTheSame(oldItem: NewsModel, newItem: NewsModel): Boolean =
        oldItem == newItem
}}

//Activity-Fragment
pharmacyViewModel.getPharmacy().observe(viewLifecycleOwner, Observer { list -(recyclerView.adapter as PharmacyAdapter).submitList(list)})

或 - 普通适配器

// 在适配器中

有趣的 updateList(list: ArrayList) {this.list.apply {clear() addAll(list)}}

//活动片段

有趣的 updateList(list: ArrayList) { this.newsAdapter.apply {updateList(list)notifyDataSetChanged()}}

newsViewModel.getData().observe(viewLifecycleOwner, Observer { newsList->updateList(newsList as ArrayList) })

于 2020-07-22T10:48:05.037 回答