如何使用 rxjava 和 room 链接查询



我需要填写对象的字段才能将其发布到 API。

我正在使用 rxjava 和房间,但我的订单链失败了

我的道

@Dao
abstract public class PokemonDao implements BaseDao<Pokemon>{
@Query("SELECT * FROM pokemons ORDER BY id ASC")
abstract public Flowable<List<Pokemon>> getAll();
}
@Dao
abstract public class NoteDao implements BaseDao<Note>{

@Query("SELECT * FROM notes WHERE idPokemon = :idPokemon ORDER BY registerDate DESC")
abstract public Flowable<List<Note>> getNotes(int idPokemon);
}

我需要创建一个对象,其中包含口袋妖怪的数据以及关联的注释列表

我在视图模型上做了以下操作

pokemonRepository.getFavourites()
.toObservable()
.flatMap(new Function<List<Pokemon>, ObservableSource<?>>() {
@Override
public ObservableSource<?> apply(List<Pokemon> favourites) throws Exception {
return Observable.fromIterable(favourites);
}
})
.flatMap(new Function<Object, ObservableSource<?>>() {
@Override
public ObservableSource<?> apply(Object o) throws Exception {
return getNotesObservable((Favourite) o);
}
})
.toList()
.toObservable()
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribeWith(new SingleObserver<List<Object>>() {
@Override
public void onSubscribe(Disposable d) {
}
@Override
public void onSuccess(List<Object> objects) {
}
@Override
public void onError(Throwable e) {
}
})

我也用这个方法

private Observable<Object> getNotesObservable(Pokemon favourite) {

Observable<Object> lolo = noteRepository.getNotes(Integer.parseInt(favourite.getId()))
.map(new Function<List<Note>, Object>() {
@Override
public Favourite apply(List<Note> notes) throws Exception {
favourite.notesList= notes;
return favourite;
}
})
.toObservable();
return lolo;
}

我的问题是在订阅与onNext方法上永远不会被调用。 我的目标是,当调用onNext时,它应该有一个口袋妖怪列表,每个口袋妖怪都应该有自己的笔记

谢谢

下面我描述没有RxJava的任务的房间式方式

假设您有以下实体:

@Entity
public class Pokemon {
@PrimaryKey public int id;
public String name;
// other fields
........
}
@Entity
public class Note {
@PrimaryKey public int noteId;
public int pokemonId;
// other fields
........ 
}

然后你可以添加另一个类(它只是一个与SQLite没有连接的类(:

public class PokemonWithNotes {
@Embedded public Pokemon pokemon; // here you'll get your pokemon
@Relation(
parentColumn = "id",
entityColumn = "pokemonId"
)
public List<Note> notesList; // here you'll het your notes' list
}

并将方法添加到您的 DAO 中:

@Transaction
@Query("SELECT * FROM Pokemon")
public List<PokemonWithNotes> getPokemonListWithNotes();

房间订单到此方法以获取口袋妖怪和笔记并连接它们(无需两个查询(

使用这种方法,您将获得包含口袋妖怪和笔记的列表。

最新更新