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

标签 android kotlin android-room rx-android android-architecture-components

我正在使用房间数据库来存储评论,并使用 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/

相关文章:

android - 我应该在 ActionCodeSettings.Builder.setAndroidPackageName() 中至少使用什么版本号?

android - 如何使用 LiveData 处理错误状态?

java - 在 Kotlin 中将函数调用分配给变量

android - 如何忽略带有房间的实体字段

android - 如何在 Room 数据库中使用创建和打开回调

android - 使用iframe API在Android手机上播放Youtube html5视频

java - 在Android中,多部分实体是否也用于下载文件,因为我看不到该类的任何示例或详细描述

更改 fragment 后隐藏的Android FAB HideBottomViewOnScrollBehavior statys

android-studio - Drop column Room迁移android

java - 如何使列表页眉和页脚不可点击?