Entity class:
@Entity
public class User {
@PrimaryKey
public int uid;
@ColumnInfo(name = "first_name")
public String firstName;
@ColumnInfo(name = "last_name")
public String lastName;
public User(int uid, String firstName, String lastName){
this.uid = uid;
this.firstName = firstName;
this.lastName = lastName;
}
}
Dao Interface:
@Dao
public interface UserDao {
@Query("SELECT * FROM User")
Flowable<List<User>> getAlls();
@Insert
Completable addData(User modelClass);
}
Database:
@Database(entities = {User.class}, version = 1)
public abstract class AppDatabase extends RoomDatabase {
private static AppDatabase instance;
static AppDatabase getDatabase(Context context) {
if (instance == null) {
instance = Room.databaseBuilder(context, AppDatabase.class, "your_db_name").createFromFile(new File("mypath")).build();
}
return instance;
}
public abstract UserDao userDao();
}
ViewModel:
public class RoomWithRxJavaViewModel extends AndroidViewModel {
private AppDatabase appDatabase;
public RoomWithRxJavaViewModel(@NonNull Application application) {
super(application);
appDatabase = AppDatabase.getDatabase(application);
}
public Flowable<List<User>> getList() {
return appDatabase.userDao().getAlls().subscribeOn(Schedulers.computation())
.observeOn(AndroidSchedulers.mainThread());
}
public Completable addData(User modelClass) {
return Completable.fromAction(() -> appDatabase.userDao().addData(modelClass))
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread());
}
}
Activity where I print results:
RoomWithRxJavaViewModel viewModel = new RoomWithRxJavaViewModel(this.getApplication());
Disposable disposable = viewModel.addData(new User(2, "btt", "bbb"))
.subscribe(
() -> { //onSucess
Toast.makeText(this, "Completed!", Toast.LENGTH_SHORT).show();
Disposable subscribe = viewModel.getList()
.subscribe(modelClasses ->
{
Toast.makeText(this, "RoomWithRx: " + modelClasses.size(), Toast.LENGTH_LONG).show();
}, e -> Toast.makeText(this, "Error: " + e.getMessage(), Toast.LENGTH_LONG).show());
}, //onError
throwable -> {
Toast.makeText(this, "Error!" + throwable.getMessage(), Toast.LENGTH_SHORT).show();
}
);
Creating a default user the insert is successful because I enter the onSucess function. I want to check the size of the updated User table but no matter how often I insert the user, the size remains 0. Why?
Your DAO:
@Insert
Single<Long> insert(User user);
Change Completable to Single as following:
public Single<Long> addData2(User user) {
return appDatabase.userDao().addData(user)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread());
}
And your modelview should look like this:
Disposable subscribe1 = viewModel.addData2(new User(4, "some", "user"))
.subscribe(
id -> { //onSucess },
throwable -> { //onerror }
);