I am using viewModel in recycler view, but its not updating only if I enter and exist screen not in screen itself:
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
viewModel = ViewModelProvider(requireActivity()).get(RideDataViewModel::class.java)
rideList.adapter = MyRideListItemRecyclerViewAdapter(viewModel.rides.value!!, object : OnItemClickListener {
override fun onItemClicked(ride: RideEntity) {
viewModel.setRide(ride)
findNavController().navigate(R.id.rideDataFragment)
}
})
viewModel.rides.observe(viewLifecycleOwner, {
if (it.isNotEmpty())
{
no_rides.visibility = View.GONE
rideList.adapter!!.notifyDataSetChanged() //Function called but no visible data
}
else
{
no_rides.visibility = View.VISIBLE
}
})
lifecycleScope.launch {
viewModel.setRides(DataBaseHelper.getAllRidesFromDB())
}
}
ViewModel:
class RideDataViewModel : ViewModel() {
var rides= MutableLiveData<List<RideEntity>>(listOf())
fun setRides(item: List<RideEntity>) {
rides.postValue(item)
}
}
You don't show your adapters code, but you need to set the adapters underlying data/list using the it
reference before calling notifyDataSetChanged
if (it.isNotEmpty()) {
no_rides.visibility = View.GONE
rideList.adapter!!.data = it // something similar to set the list in your adapter to the new values
rideList.adapter!!.notifyDataSetChanged() //Function called but no visible data
}