我想过滤一个stream(),该过滤器必须附带一个谓词,我如何才能使用RxJava实现此目的,我正在使用Room Persistence Database,如果数据库尚未包含新字段,我想添加新字段,我的问题是出在dosDatabaseContainSong()方法上。
我是RX Java的新手,代码混合了Kotlin和Java
// 1. ADD NEW SONGS TO DATABASE
songs.stream()
.filter(song -> !doesDatabaseContainSong(song, mViewModel))
.forEach(this::addSongToDatabase);
我希望以下函数(doesDatabaseContainSong)返回一个布尔值,而不是返回Single
public static boolean doesDatabaseContainSong(Song song, SongViewModel model) {
int result = model.doesDatabaseContainSong(song.getId(), Type.GOOGLE_DRIVE.name());
return result != 0;
}
视图模型
fun doesDatabaseContainSong(mId: String): Single<Int> {
return repository.doesDatabaseContainSong(mId)
}
存储库
fun doesDatabaseContainSong(mId: String): Single<Int> {
return songDao.doesDatabaseContainSong(mId)
}
DAO
@Query("SELECT COUNT(id) from song_table WHERE id = :mId")
fun doesDatabaseContainSong(mId: String): Single<Int>
答案 0 :(得分:1)
DAO(将返回类型更改为布尔型)
@Query("SELECT COUNT(id) from song_table WHERE id = :mId")
fun doesDatabaseContainSong(mId: String): Single<Boolean>
存储库(将返回类型更改为布尔值)
fun doesDatabaseContainSong(mId: String): Single<Boolean> {
return songDao.doesDatabaseContainSong(mId)
}
视图模型(将返回类型更改为布尔值)
fun doesDatabaseContainSong(mId: String): Single<Boolean> {
return repository.doesDatabaseContainSong(mId)
}
(将返回类型更改为布尔值)
public static Single<Boolean> doesDatabaseContainSong(Song song, SongViewModel model) {
return model.doesDatabaseContainSong(song.getId(), Type.GOOGLE_DRIVE.name());
}
现在的最终代码:
songs
.stream()
.flatMap(doesContainSong -> doesDatabaseContainSong(song, mViewModel))
.filter(doesContainSong -> !doesContainSong)
.forEach(this::addSongToDatabase);
希望这会有所帮助。