我正在使用Room存储有关购物车详细信息的信息。
我想在主线程中detele
记录。我遇到错误
无法访问主线程上的数据库,因为它可能长时间锁定
我检查了以下链接,但有帮助
executing delete with room (rxjava)
How to insert data and get id as out parameter in android room and rxjava 2?
DaoAccess.java
@Dao
public interface DaoAccess {
@Insert
void insertMultipleRecord(DBProducts... universities);
@Insert
void insertMultipleListRecord(List<DBProducts> universities);
@Insert
void insertOnlySingleRecord(DBProducts university);
@Query("SELECT * FROM DBProducts")
LiveData<List<DBProducts>> fetchAllData();
@Update
void updateRecord(DBProducts university);
@Delete
void deleteRecord(DBProducts university);
}
应用程序类
public class PRApp extends Application {
private static PRApp m_instance;
DBHelper dbHelper;
@Override
public void onCreate() {
super.onCreate();
mInstance = this;
prefs = new PRPrefs(this);
m_instance = this;
sDefSystemLanguage = Locale.getDefault().getLanguage();
switch (sDefSystemLanguage) {
case "en":
sDefSystemLanguageCode = "1";
break;
case "ar":
sDefSystemLanguageCode = "2";
break;
default:
sDefSystemLanguageCode = "3";
break;
}
}
public DBHelper getRoomDB() {
dbHelper = Room.databaseBuilder(getApplicationContext(),
DBHelper.class, "prasukh-db").build();
return dbHelper;
}
}
我的异步任务正常工作
new AsyncTask<Void, Void, Integer>() {
@Override
protected Integer doInBackground(Void... params) {
PRApp.getInstance().getRoomDB().daoAccess().deleteRecord(products.get(position));
return 0;
}
@Override
protected void onPostExecute(Integer agentsCount) {
Utilities.decrementBadegeCount();
productsArrayList.remove(position);
cardAdapter.notifyDataSetChanged();
notifyDataSetChanged();
hideProgressDialog();
setCartLayout();
}
}.execute();
由于我的
DAO delete
返回void
,如何在RxJava中实现呢? 最佳答案
使用fromCallable
运算符。
Observable.fromCallable(() -> {
PRApp.getInstance().getRoomDB().daoAccess().deleteRecord(products.get(position));
return true;
}).firstOrError()
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new SingleObserver<List<String>>() {
@Override
public void onSubscribe(Disposable d) {
}
@Override
public void onSuccess(List<String> strings) {
}
@Override
public void onError(Throwable e) {
}
});
// or only
.subscribe()
// But if an error occurred in delete operation the app will crash
这将执行删除操作并产生一个
Observable<Boolean>
。或者您可以使用以下命令允许访问主线程中的数据库
Room.databaseBuilder(getApplicationContext(),DBHelper.class, "prasukh-db")
.allowMainThreadQueries()
.build();
但是由于性能不建议这样做。
关于android - 使用RxJava在主线程室中执行删除,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/48237168/