gpt4 book ai didi

android - 使用 RxJava 在主线程室中执行删除

转载 作者:行者123 更新时间:2023-11-29 19:02:55 25 4
gpt4 key购买 nike

我正在使用 Room 来存储有关购物车详细信息的信息。

我想在主线程中删除记录。我收到错误

can not access database on the main thread since it may potentially lock the up for a long period of time

我检查了下面的链接但没有帮助我

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();

如何在 RxJava 中实现这一点。因为我的 DAO delete 返回 void

最佳答案

使用 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com