我正在使用房间数据库来存储评论,并使用 RxJava 作为监听器在数据库更改时做一些事情。
我不想在对表调用 delete 时调用回调,仅在调用 insert 时调用。
到目前为止我发现 Room 图书馆有 triggers
在 delete
上调用的, insert
和 update
依次调用 RxJava 方法的表。
有没有办法删除 delete
仅为 insert
触发和获取回调和 update
方法?
这是我的 CommentDAO:
@Query("SELECT * FROM comments" )
fun getAll(): Flowable<List<Comment>>
@Insert(onConflict = OnConflictStrategy.REPLACE)
fun insert(comment: Comment)
@Delete
fun delete(comment: Comment)
还有我的 RxJava 回调函数:
/**
* Inserts comment into comment database
*
* @param object that's going to be inserted to the database
*/
fun saveComment(comment: Comment) {
Observable.just(comment).subscribeOn(Schedulers.io()).map({ comment1 -> commentdb.commentDao().insert(comment1) }).subscribe()
}
/**
* Removes comment from the database
*
* @param comment object that's going to be removed
*/
fun removeComment(comment: Comment){
Observable.just(comment).subscribeOn(Schedulers.io()).map({ comment1 -> commentdb.commentDao().delete(comment1) }).subscribe()
}
fun createCommentObservable(uploader: CommentUploader) {
commentdb.commentDao().getAll().subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(
{
success -> uploader.queue(success)
}
)
}
最佳答案
你可以得到一个Flowable<List<Comment>>
通过过滤原始 getAll()
仅在插入时发出而不在删除时发出Flowable
所以只有那些 List<Comment>
通过的项目包含更多 Comment
s 比以前的 List<Comment>
.
您可以使用以下转换来实现此过滤:
- 在 flowable 前面加上一个空列表,这样我们就有了插入的基线。
- 获取
RxJava
window()
大小为 2 的 s,以便我们能够比较相邻的项目。 -
window()
返回Flowable<Flowable<Comment>>
.将其转换为Flowable<List<Comment>>
与flatMap()
和toList()
在内Flowable
. - 过滤那些代表插入的双元素窗口(第一个元素的大小小于第二个元素的大小)。
- 仅发出过滤窗口的第二个元素。
在 Kotlin 中:
fun getAllAfterInsertions() {
getAll()
.startWith(emptyList<String>()) // (1)
.window(2, 1) // (2)
.flatMap({ w -> w.toList().toFlowable() }) // (3)
.filter({ w -> w.size == 2 && w[0].size < w[1].size }) // (4)
.map({ window -> window[1] }) // (5)
}
关于android - Room 数据库的 Drop 删除触发器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47699390/