执行带有空间的删除(rxjava) [英] Executing delete with room (rxjava)

查看:145
本文介绍了执行带有空间的删除(rxjava)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在房间中,@Delete注释不发出任何东西.这就是dao的样子

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,因为我们没有排放dao.我使用以下代码在后台线程上调用deleteUser.

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);

这很好.但是,在Subscribe方法中,我现在需要访问Android UI来显示一个吐司,宣布成功删除.自然,我得到了这个异常(因为链中缺少describeOn)

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()

但是当我这样放置observeOn

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.

推荐答案

基于此问题的信息:使用Completable并订阅另一个线程,如下所示:

Using a Completable and subscribing on another thread like this:

Completable.fromAction(this::clearCachedData)
   .subscribeOn(Schedulers.io())
   .subscribe();

为我工作. clearCachedData方法在我正在调用的Room中执行查询.

worked for me. clearCachedData method executes the query in Room that I'm calling.

我的查询是:

/**
 * Delete all data in the items table.
 */
@Query("DELETE FROM items")
void deleteWeatherItems();

这篇关于执行带有空间的删除(rxjava)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆