I'm moving my application from sqlite to Firebase. Previously I would read N items from the DB to an arraylist and call notifyItemRangeInserted. Now the most convenient way to get data from Firebase delivers objects one by one. I was wondering if anyone benched the cost of calling notifyItemInserted for each list item. Is that fine or should I batch my loads? I'm displaying everything in a RecyclerView.
Based on the documentation for RecyclerView:
There are two different classes of data change events, item changes and structural changes. Item changes are when a single item has its data updated but no positional changes have occurred. Structural changes are when items are inserted, removed or moved within the data set.
notifyItemInserted : Notify any registered observers that the item reflected at position has been newly inserted
notifyItemRangeInserted : Notify any registered observers that the currently reflected itemCount items starting at positionStart have been newly inserted
Its a bit tricky to quantify and compare these two.
Based on the functionality: Both of them seems to perform same operation. They don't alter the existing items binding but rather alter existing items position.
Based on impact after notify observer: Calling notifyItemInserted in short interval would trigger the registered observers frequently. If those observers are doing some heavy computation then notifyItemInserted for each item would be expensive.
However, if you do have list that is not sequential in a range (e.g. remove item 1, 2 and 4), or if you want to perform insertion and removal simultaneously, and have it animated accordingly or you frequently modifying the adapter's dataset, efficient way would be to implement DiffUtil which is available in support library.
Most of the time our list changes completely and we set new list to
RecyclerView Adapter. And we call notifyDataSetChanged to update
adapter. NotifyDataSetChanged is costly. DiffUtil class solves that
problem now. It does its job perfectly
You can find more information here.
Related
I have a question that is more related to proper design and architecture of MVVM than to coding itself. In my project I have a situation that on ViewModel is suplying data, that are later used in RecyclerView.Adapter to create a proper view.
However I wonder if this would be also correct (from proper 'way of doing things' POV) if some of the data would be supplied in form of id's to be further fetched from Room or external server? For instance during onBindViewHolder use some LiveData with observe() to update certain fields on succesfull load.
Doing data fetch in the views is a no-go. It defeats the very purpose of MVVM and in particular the Android Jetpack efforts. One of the big reason is the data needs to survive configurations. Putting "data fetching" mechanism in the view defeats that as the view can be destroyed and recreated anytime when need be.
So I would suggest you make sure all calls to the network or any other source of data for that matter revolve around the ViewModel and never a view. Let the VM feed the data to the View through observer.
Exception to what I have just said is such use case as loading images with Picasso or Glide where by you feed them URL and they load image. But that's a different thing as they are designed to handle that.
UPDATE with followup Questions
it's ok to put observe() still inside Adapter, during the binding process?
No! Data sent to the adapter must be complete in the purpose it is supposed to serve. For example, if you have to do list app and your Top-Level Activity displays all Todos, then you must feed adapter will complete data (Title, Created time, et al).
The data that are not going to be displayed (like descriptions or sub-to-do-lists) and aren't necessary to identify specific to do should not be fetched (unless you want to store them for sole purpose of avoiding a second network call and pass them to the next activity as serialized data).
When user clicks specific To-Do, then launch new activity with its own ViewModel that will fetch details for that activity (assuming you passed some ID with intent).
If the first, then I understand that observe() should not only update data, but also populate it later to Observer and call notifyDataSetChanged(), right?
Observe is a way to post data to the view when either it have changed or the old view was destroyed and so the new view is being given the same old data that survived the "view death". So it is in the same method where updating data of the Adapter should be done and hence call to notifyDataSetChanged() or similar methods.
I hope that makes it clear.
I think it's best to keep the ViewModel separate from the Adapter. From what I'm gathering you want to basically have each list item load it's own data from Room by having each list item observe on a particular ID for that item. This sounds rather inefficient as you're basically having each item execute a query on the database (or network call) to retrieve just one item for all items that are going to be displayed, think about how it will scale if you were displaying a 100 items. I think it's best that you just execute one query to get the list of data and set the data to the list items in the adapter, keep it simple. Note that onBindViewHolder() doesn't just get called once but multiple times when you're scrolling the screen, so it could get quite ugly if you're trying to lazily load every list item.
I am using the PagedList library in my app.
It all works as expected, using the PagedListAdapter. However, I am not able to find how I can get a callback and be notified that the PagedList has been updated.
At list's ItemKeyedDataSource is used to fetch the list's data from the network. At that point, the PagedListAdapter's submitList is called, providing a PagedList of length 0. When the DataSource has fetched the data from the network, its callback.onResult() is executed and the list's UI is updated showing the fetched items. However, this does not call the submitList method, and I have not found a way to be notified in the adapter of this update, as the onCurrentListChanged is neither called. How can the Adapter be notified of such changes?
Thank you :)
You can use PagedList.addWeakCallback. You can pass a PagedList.Callback to it and listen to events such as onInserted, onChanged or onRemoved. More detail can be found in this answer
Let me just say up front that this is more of a "structural" question, and I'm not asking anybody to write code; I'm just trying to figure out how I should be structuring my application.
I'm using Android's DrawerLayout/NavigationView for my app. This means that MainActivity is the host for all my fragments.
I currently have three fragments (in reality it's many more, but they are more or less exactly like these three fragments, just for different sets of data).
ListFragment
DetailFragment
EditFragment (used for both adding and editing)
On my ListFragment I have (surprise!) a list of items. This is a LiveData collection on SharedViewModel (which is tied to MainActivity's lifecycle). When an item is tapped I pass the event through to MainActivity by means of an interface listener.
MainActivity then loads up the DetailFragment. In the same call, I load an instance of SharedViewModel (again tied to MainActivity). I set SharedViewModel.selectedItem to be the tapped item. Then, in DetailFragment's onCreate function, I get the selected item via ViewModelProviders.of(activity).get(SharedViewModel::class.java).selectedItem.
On the DetailFragment, there's an edit button. This goes through more or less the same routine described above, but loading up the EditFragment instead. When the edited/added item is saved, I add/replace the item in SharedViewModel's collection through MainActivity's interface listener.
Obviously this is not optimal for several reasons. For one, it means that I've got at least five large sets of data hanging around for MainActivity's lifecycle (the entire lifecycle of the app, essentially). Also, MainActivity grows way out of hand as I have to add more and more functions to handle events.
What I want to do is have, for example, my list of items on a ListFragmentViewModel which is tied to ListFragment's lifecycle. My selected item on a DetailFragmentViewModel, my editing item on an EditFragmentViewModel, etc.
My problem is that I'm not sure how to properly pass the data around in this case. For example, let's say I add a new item in EditFragment. How do I get that into ListFragmentViewModel's collection of items? ListFragment is in the back-stack, so its viewmodel hangs around and doesn't reload the data when it's navigated back to, since it still has the collection from before. This makes sense and is probably how it should be (after all, who wants to wait for all the data to load when they go to DetailFragment and back to ListFragment?), but it means that I don't get my new item in the collection.
That's just one example, but I'm running into quite a few issues like it (e.g. passing the selected item to DetailFragmentViewModel.)
I'm not quite sure what direction I should even be going here. Can someone more experienced help me out?
let's say I add a new item in EditFragment. How do I get that into ListFragmentViewModel's collection of items?
EditFragment tells your item repository, "yo! here's a new item!". The item repository arranges to update your backing store, plus emits an event to interested parties notifying about the data change (e.g., emits an event on an RxJava PublishSubject). The ListFragmentViewModel listens for those events and reacts accordingly.
ListFragment is in the back-stack, so its viewmodel hangs around and doesn't reload the data when it's navigated back to, since it still has the collection from before
It should be finding out about the data change from your item repository, and doing whatever makes sense to reflect that data change. That could be simply taking data from the data-change event and updating its in-memory content. That could be re-requesting information from the backing store. In principle, it could be something else.
My project uses the SQLiteCursorLoader library from commonsguy to load data from a database into a ListView. Among that data is a simple boolean (as so far as SQLite supports booleans... that is, a number that only ever is 0 or 1) that tells the state of a checkbox. If I change the state of a checkbox in a list and then scroll the item off the list, the list item returns to the state it has when the cursor was passed in, despite the fact that the underlying database has changed. If I change the state of a bunch of checkboxes and then activate the list's MultiChoiceMode, all the items displayed will revert back to the state they were in when the cursor was originally passed in, despite the fact that the underlying database has changed.
Is there a way to refresh the cursor? Cursor.requery() is deprecated, and I don't want to have to create a new Cursor each time a checkbox is checked, which happens a lot. I'm also unsure of how calling restartLoader() several times would work, performance-wise, especially since I use onLoadFinish() to perform some animations.
Is there a way to refresh the cursor?
Call restartLoader() to have it reload the data.
I don't want to have to create a new Cursor each time a checkbox is checked, which happens a lot
Used properly, a ListView maintains the checked state for you. You would do this via android:choiceMode="multipleChoice" and row Views that implement Checkable. The objective is to not modify the database until the user has indicated they are done messing with the checklist by one means or another (e.g., "Save" action bar item).
I'm also unsure of how calling restartLoader() several times would work, performance-wise, especially since I use onLoadFinish() to perform some animations.
Don't call it several times. Ideally, call it zero times, by not updating the database until the user is done, at which point you are probably transitioning to some other portion of your UI. Or, call it just once per requested database I/O (e.g., at the point of clicking "Save"). Or, switch from using a CursorAdapter to something else, such as an ArrayAdapter on a set of POJOs you populate from the Cursor, so that the in-memory representation is modifiable in addition to being separately persistable.
What is the difference? The android documentation doesn't have a description for notifyDataSetInvalidated(). I was thinking maybe you call that function to notify all registered listeners, but use notifyDataSetChanged() to not notify them?
Changed means the data set changed. Individual items updated, or items were added or removed. Invalidated means the data source is no longer available.