简体   繁体   中英

Android RecyclerView MVVM where to update Adapter with notifyDataSetChanged

Where should I call any form of notifyDataSetChanged() on my adapter? The data source is populated asynchronously because I fetch the data from the web.

The adapter belongs to the view. However the data source of the adapter belongs to the viewmodel. The viewmodel should not have a reference to the view.

The only way of updating my adapter I can think of is using a broadcast receiver and I don't think that is a recommended solution as well.

MyFragment.kt

override fun onViewCreated(...) {
    //...
    recyclerView.adapter = myItemAdapter
}

MyViewModel.kt

private val _myItems = mutableListOf<Item>()
val myItems: List<Item> = _myItems 

private fun someMethod() {
    viewModelScope.launch {
        _myItems.addAll(itemsRepository.getSomeItems())
    }
}

Thanks in advance

EDIT:

I don't want to encapsulate the data source in a LiveData and observe it for changes in the view, because the data source is really just initialized once and never updated again. Is there another way of doing it or do I have to use LiveData ?

declare _myItems by MutableLiveData

val _myItems = MutableLiveData<MutableList<Item1>>()

and observe it in fragment

viewModel._myItems.observe(this, Observer { itemss ->
    myItemAdapter.set(items)
    myItemAdapter.notifyDataSetChanged()
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM