代码之家  ›  专栏  ›  技术社区  ›  Nominalista

DAO实现中的可完成删除函数产生IllegalStateException

  •  2
  • Nominalista  · 技术社区  · 6 年前

    假设我们有简单的DAO接口:

    @Dao
    interface MyDao {
        @Delete
        fun delete(entity: MyEntity): Completable
    }
    

    我们期望从Room中,它会生成返回的函数 Completable . 本协议的执行 完全的 应该从数据库中删除实体。

    现在我们打电话 delete

    // Called in the main thread
    myDao.delete(myEntity)
        .subscribeOn(Schedulers.background())
        .subscribe()
    

    问题是这个调用导致 IllegalStateException

    Cannot access database on the main thread since it may potentially lock the UI for a long period of time.
    

    有趣的是,其他函数如select(返回 Single<MyEntity> 非法状态例外 在删除实现中:

    public SupportSQLiteStatement acquire() {
        assertNotMainThread();
        return getStmt(mLock.compareAndSet(false, true));
    }
    

    问题是,这是一个bug还是我应该用另一种方式调用delete,比如: Completale.defer { myDao.delete(myEntity)) } ?

    编辑

    更具体地说:我使用自定义查询进行删除( "DELETE FROM myentities WHERE id = :id )下面是生成的代码:

    @Override
    public Completable deleteByIdInternal(final long id) {
      final SupportSQLiteStatement _stmt = __preparedStmtOfDeleteByIdInternal.acquire();
      int _argIndex = 1;
      _stmt.bindLong(_argIndex, id);
      return Completable.fromCallable(new Callable<Void>() {
        @Override
        public Void call() throws Exception {
          __db.beginTransaction();
          try {
            _stmt.executeUpdateDelete();
            __db.setTransactionSuccessful();
            return null;
          } finally {
            __db.endTransaction();
            __preparedStmtOfDeleteByIdInternal.release(_stmt);
          }
        }
      });
    }
    
    0 回复  |  直到 6 年前