Reputation: 613
I just wondered if there is a way to sort a RealmList
asynchronously on Android.
Say I have a realm object called diaryEntry
which contains a RealmList
of Entry
objects:
RealmList<Entry> entries;
public RealmList<Entry> getEntries() { return entries; }
If i want to sort the RealmList I simply call sort and thats it, it works fine.
RealmResults<Entry> sortedEntries = diaryEntry.getEntries().sort("time");
mvpView.bindAndShowEntryList(sortedEntries);
The above code however is executed in a Fragment´s onResumeFragment()
method which gets called when the Fragment becomes visible (it´s a custom lifecycle method I introduced) in a ViewPager. So obviously it would be nice if I could sort the data in the background and when the fragment becomes visible simply bind the results to the view.
So I came up with a second solution below:
entries = realm.where(Entry.class)
.equalTo("dateId", dateId)
.findAllSortedAsync("time");
Note: dateId
is an integer and is a unique ID for every Fragment
in the ViewPager
.
This way I had to add a new indexed integer field dateId to the Entry.class.
public class Entry extends RealmObject {
// Other fields ...
@Index
private int dateId;
My question: Is there a way to sort a RealmList
asynchronously?
If not, which approach may be better? The first one which sorts the entries on the UI thread but has instant access to a RealmList
containing all the corresponding Entry
objects (in average 10-15 Entry objects).
Or the second approach, which has to find all corresponding Entry
objects first by their dateId
, but does all of that async without blocking the UI thread?
Note: In average there are about 10-15 Entry
objects for every unique dateId
, so if a normal user is using my app for 2 years and adds about 15 entries every day there will be about 11000 Entry
objects in the database. This is obviously a pretty high assumption as no user will add entries every day and not even that much.
Upvotes: 1
Views: 286
Reputation: 3565
You can do:
RealmResults<Entry> sortedEntries = diaryEntry.getEntries()
.where()
.findAllSortedAsync("time");
This will create a query based on your entries list and the query will be executed in the background thread.
Upvotes: 1