I am getting the new list with new item at the start in my live data and then using its data to update the adapter
viewModel.myLiveData.observe { this, Observer
submitList
does its work on a background thread, so there will always be race conditions that delays can't solve. Fortunately, we can use a RecyclerView.AdapterDataObserver
callback to be informed when the list calculations are complete:
yourRecyclerViewAdapter.registerAdapterDataObserver(object: RecyclerView.AdapterDataObserver() {
override fun onChanged() {
recycler_view_list.scrollToPosition(0)
}
override fun onItemRangeRemoved(positionStart: Int, itemCount: Int) {
recycler_view_list.scrollToPosition(0)
}
override fun onItemRangeMoved(fromPosition: Int, toPosition: Int, itemCount: Int) {
recycler_view_list.scrollToPosition(0)
}
override fun onItemRangeInserted(positionStart: Int, itemCount: Int) {
recycler_view_list.scrollToPosition(0)
}
override fun onItemRangeChanged(positionStart: Int, itemCount: Int) {
recycler_view_list.scrollToPosition(0)
}
override fun onItemRangeChanged(positionStart: Int, itemCount: Int, payload: Any?) {
recycler_view_list.scrollToPosition(0)
}
})
viewModel.myLiveData.observe { this, Observer { myList ->
adapter.submitList(myList)
}