Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Executing delete with room (rxjava)

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.
like image 544
Muhammad Ahmed AbuTalib Avatar asked Dec 21 '17 08:12

Muhammad Ahmed AbuTalib


1 Answers

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();
like image 86
909080 Avatar answered Oct 22 '22 01:10

909080