In room the @Delete
annotation doesn't emit anything. This is what the dao
looks like
@Dao
public interface UserDao {
@Delete
void deleteUser(User user);
//We can't use Maybe or Single or anything here
}
This makes it a problem while doing something like
userRepository.deleteUser().subscribeOn
since we have no emission coming the dao
. I use the following code to call deleteUser on a background thread.
Observable.just(appDatabase).
subscribeOn(SchedulerProvider.getInstance().computation()).
subscribe(db -> {
userRepository.logoutUser(loggedUser.getLoggedInUser());
loggedUser.setLoggedInUser(null);
}, this::handleError);
This works fine. However, in the subscribe method I now need to access the Android UI to display a toast announcing a successful delete. Naturally, I get this exception (since the observeOn is missing from the chain)
java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
However when I put the observeOn
like this
Observable.just(appDatabase).
subscribeOn(SchedulerProvider.getInstance().computation()).
observeOn(SchedulerProvider.getInstance().ui()).
subscribe(db -> {
userRepository.logoutUser(loggedUser.getLoggedInUser());
loggedUser.setLoggedInUser(null);
Message message = new Message(R.string.user_logged_out_msg);
message.setMessageType(Message.MessageType.SUCCESS_MESSAGE);
view.showMessages(Arrays.asList(message)); //this leads to a taost
}, this::handleError);
I strangely get this exception:
cannot access database on the main thread since it may potentially lock the UI for a long period of time.
Based on info from this question: Run Void Method in Background (StackOverflow)
Using a Completable and subscribing on another thread like this:
Completable.fromAction(this::clearCachedData)
.subscribeOn(Schedulers.io())
.subscribe();
worked for me. clearCachedData
method executes the query in Room that I'm calling.
My query is:
/**
* Delete all data in the items table.
*/
@Query("DELETE FROM items")
void deleteWeatherItems();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With