使用Kotlin实现RecyclerView的MVVM设计模式

3

我是Kotlin的初学者,尝试在Android开发中实现MVVM设计模式。我必须在片段中实现Recyclerview。

由于API调用在ViewModel中进行观察,我们如何从ViewModel类设置适配器的值到RecyclerView呢?

我的片段类如下所示:

class NotesFragment : Fragment() {

lateinit var binding:FragmentNotesBinding
lateinit var viewModel:NoteListViewModel

companion object {
    fun newInstance(param1: String): NotesFragment {
        val fragment = NotesFragment()
        val args = Bundle()
        fragment.arguments = args
        return fragment
    }
}

override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
                          savedInstanceState: Bundle?): View? {
    binding = DataBindingUtil.inflate(inflater,R.layout.fragment_notes,container,false)
    viewModel = NoteListViewModel(binding)
    return binding.root
}

我们将绑定对象传递给ViewModel类并从ViewModel类中再次更新viewModel对象,这是一种好的实践吗?

 private fun onSuccess(success: NoteResponse?) {
    dataVisibility.value=View.VISIBLE
    success.let {
        noteAdapter= noteAdapter(documentResponse?.result,mContext)
        binding.viewModel=this
    }
}
1个回答

6
MVVM的核心是关注点分离。ViewModel不应该持有任何对View(Activity/Fragment)的引用。同样,您的数据/存储库层也不应该持有ViewModel的引用。
因此,为了实现数据流,您可以使用来自Android架构组件的Reactive Observables(Rx)/LiveData来传递数据。
1)在您的ViewModel中创建MutableLiveData。
2)使用API响应模型设置MutableLiveData。
3)在您的Fragment中观察MutableLiveData以获取响应数据。
4)使用数据在您的Fragment内部设置适配器。
请查看ViewModel - Developer document以更好地理解。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接