在Android中使用RxJava2插入SQLiteDatabase

时间:2018-06-18 12:58:55

标签: android rx-java2 rx-android

我在android中学习 RxJava2 。任何人都可以解释我如何使用 RxJava2 将数据插入SQLiteDatabase。 这是我试图使用的代码示例,但它将数据六次插入数据库;

//的OnClick

getCompletableObservable()
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(getCompletableObserver());

//可观察

private Completable getCompletableObservable(){
    return Completable.create(new CompletableOnSubscribe() {
        @Override
        public void subscribe(CompletableEmitter emitter) throws Exception {
            addData();
            if(!emitter.isDisposed())
                emitter.onComplete();
        }
    });
}

//观察

CompletableObserver getCompletableObserver(){
    return new CompletableObserver() {
        @Override
        public void onSubscribe(Disposable d) {

        }

        @Override
        public void onComplete() {
            showMessage("Student Added Sucessfully");
        }

        @Override
        public void onError(Throwable e) {
            showMessage(e.getMessage()+"");
        }
    };
}

//添加方法

try {
        DatabaseHelper db = new DatabaseHelper(DemoRxJava.this);
        db.open();
        String c = db.AddData(new Student(random.nextInt(1000)+"",SName.getText().toString(),SContact.getText().toString(),SEmail.getText().toString()));
        Log.d("StudentData",c);
        db.close();
    }catch (Exception e){

    }

1 个答案:

答案 0 :(得分:1)

使用Room Persistence library。它的创建是为了简化与数据库的交互。它支持使用RxJava和LiveData包装数据。

检查the Documentation开始使用

基本上,您希望创建将抽象表并将表示单个行对象的Entity类。例如,这显示了名为users的表的用户实体,以及作为PK的表。

@Entity(tableName="users")
public class User {
    @PrimaryKey
    private int uid;

    @ColumnInfo(name = "first_name")
    private String firstName;

    @ColumnInfo(name = "last_name")
    private String lastName;

    // Getters and setters are ignored for brevity,
    // but they're required for Room to work.
}

然后定义将包含查询定义的DAO类。您将使用此接口的对象进行实际查询。房间将为您制作具体的课程

@Dao
public interface UserDao {
    @Query("SELECT * FROM user")
    List<User> getAll();

    @Query("SELECT * FROM user WHERE uid IN (:userIds)")
    List<User> loadAllByIds(int[] userIds);

    @Query("SELECT * FROM user WHERE first_name LIKE :first AND "
           + "last_name LIKE :last LIMIT 1")
    User findByName(String first, String last);

    @Insert
    void insertAll(User... users);

    @Delete
    void delete(User user);
}

最后,您创建了用于实际查询数据库的数据库对象。该类是抽象的,Room也将为您创建具体的类。它包含创建DAO的方法,您可以根据需要命名方法。

@Database(entities = {User.class}, version = 1)
public abstract class AppDatabase extends RoomDatabase {
    public abstract UserDao userDao();
}

现在假设我

AppDatabase db = Room.databaseBuilder(getApplicationContext(),
        AppDatabase.class, "databaseName.db").build(); //Most of the time I have used this, it is a Singleton.

List<User> users = db.userDao().getAll();
for(User u : users)
{
    Log.d("SQLITE_ROOM_DATA", u.firstName);
}

这里我们返回了简单的List<User>,但是Room允许你用RxJava Observables包装它们,如Flowable<List<User>>或Architecture component livedata LiveData<List<User>>

要使用Room,您需要将依赖项添加到您的gradle中,如下所示:

dependencies {
    def room_version = "1.1.0" // or, for latest rc, use "1.1.1-rc1"

    implementation "android.arch.persistence.room:runtime:$room_version"
    annotationProcessor "android.arch.persistence.room:compiler:$room_version"

    // optional - RxJava support for Room
    implementation "android.arch.persistence.room:rxjava2:$room_version"
    // Test helpers
    testImplementation "android.arch.persistence.room:testing:$room_version"
}