我需要从Realm数据库加载排序的数据。我试图直接加载数据并将值发布到MutableLiveData:
mTracks.postValue(mRepository.getAllSorted(sortingDirection, sortedBy));
这是RealmRepository:
public List<Track> getAllSorted(int sortingDirection, int sortedBy) {
return mRealm.where(Track.class).sort("date", Sort.ASCENDING).findAll();
}
但这给出了错误:
IllegalStateException:来自错误线程的领域访问。领域 对象只能在创建对象的线程上访问。
然后,我尝试了不同的方法来解决此问题,并从Realm团队获得了不错的帖子:
https://academy.realm.io/posts/android-architecture-components-and-realm/
根据我创建LiveRealmData的帖子:
public class LiveRealmData<T extends RealmModel> extends MutableLiveData<RealmResults<T>> {
private RealmResults<T> results;
private final RealmChangeListener<RealmResults<T>> listener =
new RealmChangeListener<RealmResults<T>>() {
@Override
public void onChange(RealmResults<T> results) {
setValue(results);
}
};
public LiveRealmData(RealmResults<T> realmResults) {
results = realmResults;
}
@Override
protected void onActive() {
results.addChangeListener(listener);
}
@Override
protected void onInactive() {
results.removeChangeListener(listener);
}
}
并将RealmRepository部分更改为以下代码:
public LiveRealmData<Track> getAllSorted(int sortingDirection, int sortedBy) {
return asRealmLiveData(mRealm.where(Track.class).sort("date", Sort.ASCENDING).findAllAsync());
}
private LiveRealmData asRealmLiveData(RealmResults<Track> realmResults) {
return new LiveRealmData<>(realmResults);
}
在ResultsViewModel中,我正在获取LiveRealmData并尝试将其转换为MutableLiveData:
public void loadTracksSorted(int sortingDirection, int sortedBy) {
LiveRealmData<Track> tracks = mRepository.getAllSorted(sortingDirection, sortedBy);
mTracks = (MutableLiveData<List<Track>>) Transformations.map(tracks, new Function<RealmResults<Track>, List<Track>>() {
@Override
public List<Track> apply(RealmResults<Track> tracks) {
List<Track> trackList = new ArrayList<>();
for(Track track: tracks){
trackList.add(track);
}
return trackList;
}
});
}
但是结果为空。
我的问题:如何使用Transformations.map方法将数据发布到MutableLiveData?