I am Using Room Persistent Data of Android, to store data coming from the server - locally. In addition, I am using MVVM pattern, recommended by Android official docs, thus my recyclerView gets displayed inside a LiveData Observer something like this:
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.activity_feed, container, false);
((App)getActivity().getApplication()).getmAppComponent().inject(this);
rvFeed = view.findViewById(R.id.rvFeed);
mLinearLayoutManager = new LinearLayoutManager(getActivity());
rvFeed.setLayoutManager(mLinearLayoutManager);
feedAdapter = new FeedAdapter(this);
feedAdapter.setRV(rvFeed);
mFactory = new PostsViewModelFactory(postRepository);
mViewModel = ViewModelProviders.of(this, mFactory).get(PostsViewModel.class);
mViewModel.init();
mViewModel.getPostsLiveData().observe(this, new Observer<List<Post>>() {
@Override
public void onChanged(@Nullable List<Post> posts) {
feedAdapter.setPostsList(posts);
if (firstLaunch) {
rvFeed.setAdapter(feedAdapter);
firstLaunch = false;
}
loading = true;
}
});
return view;
}
The mViewModel.getPostsLiveData()
is bassically retrieving LiveData from Room (via repository), thus, any new data added to Room triggers the LiveData Observer, and the feedAdapter
repopulates the recyclerView(i.e. setPostsLists()
which in return calls notifyDataSetChanged()
).
But as you can notice the new fresh data added to room won't be displayed as first item in the recyclerView since it doesn't get added to the Adapter directly [hence, I cannot call notifyItemInserted(0)
], but rather to Room (local storage).
So my question is, what's the best way to add to the local storage (Room) but in addition to force the item to be displayed as first in the recyclerView when it get's re populated when the LiveData observer get's triggered?
Thanks in advance :)