@Dao
public interface BookCaseDao {
@Query(“SELECT * FROM user”)
Flowable<List> getUser();
@Insert(onConflict = OnConflictStrategy.REPLACE)
Completable insert(User user);
}
3、创建RoomDatabase抽象类,供数据的操作使用。根据官网提示:获取数据库操作对象采用单例,节省内存开销。
@database注解表示RoomDatabase数据库对象,entities属性表示一张或多张表,version是版本号,
exprotSchema=false 不导出数据库到本地文件。
import android.content.Context;
import androidx.room.Database;
import androidx.room.Room;
import androidx.room.RoomDatabase;
import com.example.model.bean.User;
@Database(entities = {User.class},
version = 1,
exportSchema = false)
public abstract class AppDatabase extends RoomDatabase {
private static volatile AppDatabase INSTANCE;
public abstract BookCaseDao bookCaseDao();
public static AppDatabase getInstance(Context context) {
if (INSTANCE == null) {
synchronized (AppDatabase.class) {
if (INSTANCE == null) {
INSTANCE = Room.databaseBuilder(context,
AppDatabase.class, “user.db”).build();
}
}
}
return INSTANCE;
}
}
4、创建module:
import com.example.model.bean.User;
import java.util.List;
public interface UserIntFac {
void users(List users);
void addUserSuccess();
}
4、创建控制层presenter,将module作为控制层数据的回调:
import android.content.Context;
import com.example.model.bean.User;
import com.example.model.db.AppDatabase;
import com.example.userxroomhandledata.module.UserIntFac;
import java.util.List;
import io.reactivex.Completable;
import io.reactivex.Flowable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.functions.Action;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;
public class UserPresenter {
public void addUser(User user) {
Completable insert = AppDatabase.getInstance(context).bookCaseDao().insert(user);
addDisposable(insert, new Action() {
@Override
public void run() throws Exception {
if (userIntFac != null) {
userIntFac.addUserSuccess();
}
}
});
}
public void getUsers() {
Flowable<List> users = AppDatabase.getInstance(context).bookCaseDao().getUser();
addDisposable(users, new Consumer<List>() {
@Override
public void accept(List users) throws Exception {
if (userIntFac != null) {
userIntFac.users(users);
}
}
});
}
public void addDisposable(Flowable flowable, Consumer consumer) {
compositeDisposable.add(flowable
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(consumer));
}
public void addDisposable(Completable completable, Action action) {
compositeDisposable.add(completable
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(action));
}
public UserPresenter(Context context, UserIntFac userIntFac) {
this.context = context;
this.userIntFac = userIntFac;
}
private Context context;
private UserIntFac userIntFac;