如何在android room和rxjava 2中插入数据并获取id作为out参数? [英] How to insert data and get id as out parameter in android room and rxjava 2?
问题描述
插入查询
@Insert(onConflict = OnConflictStrategy.REPLACE)
long insertProduct(Product product); //product id is auto generated
视图模型
public Completable insertProduct(final String productName) {
return new CompletableFromAction(() -> {
Product newProduct = new Product();
newProduct.setProductName(productName);
mProductDataSource.insertOrUpdateProduct(newProduct);
});
}
在我调用上述函数的活动中,我使用了CompositeDisposable.
In activity where I called this above function I used CompositeDisposable.
CompositeDisposable mDisposable = new CompositeDisposable();
mDisposable.add(mViewModel.insertProduct(productName))
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(() ->{} ,throwable -> Log.e(TAG, "Error msg", throwable)));
我实施方式有误吗?
推荐答案
根据文档.如果@Insert方法仅接收1个参数,则它可以返回long,它是插入项的新rowId.如果参数是数组或集合,则应返回long []或List.由于您仅插入一项,因此该方法将仅返回一个rowID.
According to docs. If the @Insert method receives only 1 parameter, it can return a long, which is the new rowId for the inserted item. If the parameter is an array or a collection, it should return long[] or List instead. Since you insert only one item, the method will return only one rowID.
所以,尝试这个
Single.fromCallable(new Callable<Long>() {
@Override
public Long call() throws Exception {
return productDao.insertProduct(new Product()));
}
})
.subscribe(id -> {
} ,throwable -> Log.e(TAG, "Error msg", throwable)))
您也可以使用 Observable
或 Maybe
.但是我认为 Single
更合适,因为在您的情况下,id是自动生成的,插入应始终完成.
You could use Observable
or Maybe
as well. But I think Single
fits better since in your case the id is autogenerated and the insertion should always complete.
这篇关于如何在android room和rxjava 2中插入数据并获取id作为out参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!