gpt4 book ai didi

android - Room 数据库的 Drop 删除触发器

转载 作者:行者123 更新时间:2023-11-29 19:04:47 37 4
gpt4 key购买 nike

我正在使用房间数据库来存储评论,并使用 RxJava 作为监听器在数据库更改时做一些事情。

我不想在对表调用 delete 时调用回调,仅在调用 insert 时调用。

到目前为止我发现 Room 图书馆有 triggersdelete 上调用的, insertupdate依次调用 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> .

您可以使用以下转换来实现此过滤:

  1. 在 flowable 前面加上一个空列表,这样我们就有了插入的基线。
  2. 获取RxJava window()大小为 2 的 s,以便我们能够比较相邻的项目。
  3. window()返回 Flowable<Flowable<Comment>> .将其转换为 Flowable<List<Comment>>flatMap()toList()在内Flowable .
  4. 过滤那些代表插入的双元素窗口(第一个元素的大小小于第二个元素的大小)。
  5. 仅发出过滤窗口的第二个元素。

在 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/

37 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com