Reputation: 199
So I have two DAO functions for inserting a new user:
@Insert(onConflict = OnConflictStrategy.REPLACE)
Completable addData(User user);
@Insert(onConflict = OnConflictStrategy.REPLACE)
Single<Long> insert(User user);
The difference is that one function returns a completable
and the other one a Single<Long>
where Long
equals the id of the new inserted user.
Corresponding ViewModel
functions:
public Completable addData(User modelClass) {
return Completable.fromAction(() -> appDatabase.userDao().addData(modelClass))
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread());
}
public Single<Long> addData2(User user) {
return appDatabase.userDao().insert(user)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread());
}
Last but not least the subscribe method in my android activity:
viewModel.addData(new User( ""+myEntireName.getText().toString(), "jlk"))
.subscribe(
() -> {
Toast.makeText(this, "Jähgermeister!!!!!", Toast.LENGTH_LONG).show();
},
throwable -> {
Toast.makeText(this, "Error!" + throwable.getMessage(), Toast.LENGTH_SHORT).show();
});
viewModel.addData2(new User( ""+myEntireName.getText().toString(), "jlk"))
.subscribe(
newI -> { //onSucess
Toast.makeText(this, "Yeah i work: " + newI, Toast.LENGTH_LONG).show();
}, //onError
throwable -> {
Toast.makeText(this, "Error!" + throwable.getMessage(), Toast.LENGTH_SHORT).show();
});
So here is the issue: The Insert function which returns a Completable
prints the Toast message but the user is not actually insertet. But if I use the function which returns a Single<Long>
the User is inserted. Same goes for delete.
What can be the cause? Can Insert only work with Single<Long>
?
Upvotes: 3
Views: 152
Reputation: 94961
This line is the source of the issue:
return Completable.fromAction(() -> appDatabase.userDao().addData(modelClass))
appDatabase.userDao().addData()
returns a Completable
. Putting it inside of fromAction()
means you will not subscribe to the Completable
it returns, which means whatever work it's supposed to do will not actually happen. You need to use something like Completable.defer(() -> ...)
instead, which will actually subscribe to the Completable
returned by the call to addData
.
Upvotes: 2