How to insert data and get id as out parameter in android room and rxjava 2?

假装没事ソ 提交于 2019-12-12 19:37:27

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!