问题
Insert query
@Insert(onConflict = OnConflictStrategy.REPLACE)
long insertProduct(Product product); //product id is auto generated
view model
public Completable insertProduct(final String productName) {
return new CompletableFromAction(() -> {
Product newProduct = new Product();
newProduct.setProductName(productName);
mProductDataSource.insertOrUpdateProduct(newProduct);
});
}
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)));
Am I implementing in wrong way?
回答1:
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.
So, try this
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)))
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.
来源:https://stackoverflow.com/questions/46754378/how-to-insert-data-and-get-id-as-out-parameter-in-android-room-and-rxjava-2