无法使用RxJava Completable在Room中添加数据

时间:2019-07-19 06:33:54

标签: android rx-java2

我正在使用MVVM架构模式制作应用程序,试图使用RxJava在会议室数据库中添加数据,但是在lambda表达式下显示红线

  

lambda表达式中的返回类型错误:void无法转换为Object。

下面是我的代码:

UserDao.java

@Dao
public interface UserDao {

@Insert
void insert(User user);

@Query("SELECT * FROM Users ORDER BY id DESC")
Flowable<List<User>> getAllUsers();

} 

UserRepository.java

public class UserRepository {

private UserDb userDb;
private UserDao userDao;
private Flowable<List<User>> allUsers;

public UserRepository(Application application) {

    userDb = UserDb.getInstance(application);
    userDao = userDb.userDao();
    allUsers = userDao.getAllUsers();
}

public void insert(final User user){

   Completable.fromCallable(() -> userDb.userDao().insert(user))
                            .subscribeOn(Schedulers.io())
                            .observeOn(AndroidSchedulers.mainThread())
                            .subscribe(new CompletableObserver() {
                                @Override
                                public void onSubscribe(Disposable d) {

                                }

                                @Override
                                public void onComplete() {

                                }

                                @Override
                                public void onError(Throwable e) {

                                }
                            });
    }
}

请让我知道我做错了什么。任何帮助将不胜感激。

谢谢

1 个答案:

答案 0 :(得分:3)

您应该使用@Field("description") private String description; 而不是Completable.fromCallable,它不需要lambda即可返回某些内容。

要在插入完成或失败时显示敬酒:

Completable.fromAction

您的活动内:

public class UserRepository {

private UserDb userDb;
private UserDao userDao;
private Flowable<List<User>> allUsers;

    public UserRepository(Application application) {

        userDb = UserDb.getInstance(application);
        userDao = userDb.userDao();
        allUsers = userDao.getAllUsers();
    }

    public Completable insert(final User user){

       return Completable.fromAction(() -> userDb.userDao().insert(user))
                                .subscribeOn(Schedulers.io())
                                .observeOn(AndroidSchedulers.mainThread());
    }
}

如果您不想在活动中调用插入:

您还可以将对应用程序的引用保存在存储库中

    public void onInsertClicked(){
        userRepository = //get your repository instance.
        //remember to dispose this disposable when activity destroyed, otherwise the onComplete callback will leak reference to our activity.
        Disposable disposable = userRepository.subscribe(() -> Toast.makeText(this, "Completed!", Toast.LENGTH_SHORT).show(), 
                throwable -> Toast.makeText(this, "Error!", Toast.LENGTH_SHORT).show());
    }