我在一个 android 项目中使用 RxJava 和 Realm 数据库。但有时按下按钮没有响应,你必须多次这样做才能让它在某个时候工作,并且 android 日志说 xxx 帧已跳过。我知道这与滥用 UI 线程有关。这是我的一些要求,有人可以告诉我他们有什么问题吗?Realm 希望我在使用响应的同一线程上执行 IO 请求(虽然不太确定)。
public Flowable<List<ClothingItem>> getClothingItemsLocal() {
return Flowable.just(dbProvider.getClothingItems(mSortType));
}
public Flowable<List<ClothingItem>> getClothingItemsRemote() {
return clothingService.getAll("Bearer " + preferencesManager.getToken())
.map(response -> response.items)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.doOnSuccess(clothingItems -> {
dbProvider.clearClothingItems();
dbProvider.saveOrUpdateClothingItems(clothingItems);
})
.toFlowable()
.map(remoteItems -> dbProvider.getClothingItems(mSortType));
}
public Flowable<ClothingItem> getClothingItem(@NonNull final String id) {
return getClothingItemRemote(id)
.startWith(dbProvider.getClothingItem(id))
.onErrorReturn(throwable -> dbProvider.getClothingItem(id));
}
getAll 方法与改造。
@GET(BuildConfig.BASE_API_PATH + "clothing_items")
Single<GetClothingItemsResponseModel> getAll(@Header("Authorization") String token);
领域提供者方法:
public void saveOrUpdateEvents(List<Event> data) {
realmInstance.executeTransaction(realm -> {
for (Event event : data) {
if (!TextUtils.isEmpty(event.date)) {
Date date = DateUtils.getFullDate(event.date);
Timber.d("date %s", date.toString());
event.timestamp = date;
}
Event cashedEvent = getEvent(event.id);
if (cashedEvent.id != null) {
event.eventClothingItems = cashedEvent.eventClothingItems;
event.tags = cashedEvent.tags;
event.location = cashedEvent.location;
}
}
realm.delete(Event.class);
realm.insertOrUpdate(data);
});
}
public void clearClothingItems() {
realmInstance.executeTransaction(realm -> {
realm.delete(ClothingItem.class);
});
}