簡體   English   中英

從 dao 獲取並使用 RxJava 插入新線程

[英]Get from dao and insert in new thread with RxJava

我有個問題。 我想在新線程中從我的 dao 添加我的插入方法。 但我不能使用訂閱方法。 我收到一條錯誤消息。 因為我的 Note class 沒有實現 Observable 接口。

我的筆記存儲庫 class

public class NoteRepository {

    private NoteDao noteDao;
    private LiveData<List<Note>> allNotes;

    public NoteRepository(Application application) {
        NoteDatabase database = NoteDatabase.getInstance(application);
        noteDao = database.noteDao();

        allNotes = noteDao.getAllNotes();
    }

    public Observable<Note> insert(Note note) {
        return Observable.fromIterable(allNotes.getValue())
                .subscribeOn(Schedulers.newThread())
                .observeOn(AndroidSchedulers.mainThread());
    }

    public Observable<Note> update(Note note) {
        
    }

    public Observable<Note> delete(Note note) {

    }

    public void deleteAllNotes() {

    }

    public LiveData<List<Note>> getAllNotes() {
        return allNotes;
    }
}

我的 NoteDao 界面

    @Dao
    public interface NoteDao {
    
        @Insert
        Observable<Note> insert(Note note);
    
        @Update(onConflict = OnConflictStrategy.IGNORE)
        Observable<Note> update(Note note);
    
        @Delete
        void delete(Note note);
    
        @Query("DELETE FROM note_table")
        void deleteAllNotes();
    
        @Query("SELECT * FROM note_table ORDER BY priority DESC")
        LiveData<List<Note>> getAllNotes();
}

嘗試返回Completable並更新insert方法以添加Note

public Completable insert(Note note) {
    return Completable.fromAction(new Action() {
        @Override
        public void run() throws Exception {
          noteDao.getAllNotes();
        }.subscribeOn(Schedulers.io())
         .observeOn(AndroidSchedulers.mainThread());
}

我還建議在subscribeOn中使用Schedulers.io 它類似於newThread ,除了io回收線程。

NoteDao中。 您不需要從insertupdate方法返回Observable<Note> 您已經有了將其作為參數傳遞的注釋:

    @Insert
    void insert(Note note);

    @Update(onConflict = OnConflictStrategy.IGNORE)
    void update(Note note);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM