android的触发器,关于android:删除Room数据库的触发器
我正在使用会议室数据库来存储注释,并且在数据库更改时使用RxJava作为侦听器来做一些事情。我不想在表上调用delete时不调用回调,仅当调用insert时。到目前为止,我发现Room库具有在表的delete,insert和update上调用的triggers,这些表又调用RxJava的方法。有什么方法可以删除delete触发器并仅为insert和update方法获取回调?这是我的CommentD
我正在使用会议室数据库来存储注释,并且在数据库更改时使用RxJava作为侦听器来做一些事情。
我不想在表上调用delete时不调用回调,仅当调用insert时。
到目前为止,我发现Room库具有在表的delete,insert和update上调用的triggers,这些表又调用RxJava的方法。
有什么方法可以删除delete触发器并仅为insert和update方法获取回调?
这是我的CommentDAO:
@Query("SELECT * FROM comments" )
fun getAll(): Flowable>
@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)
}
)
}
通过过滤原始的getAll() Flowable,可以获得仅在插入时而不在删除时发出的Flowable>,这样,只有那些List项通过的包含比以前的List更多的Comment传递。
您可以通过以下转换实现此过滤:
在flowable之前添加一个空列表,以便为插入提供基线。
获得大小为2的RxJava window(),这样我们就可以比较相邻的项目。
window()返回Flowable>。使用内部Flowable上的flatMap()和toList()将其转换为Flowable>。
过滤那些代表插入的2元素窗口(第一个元素的大小小于第二个元素的大小)。
仅发射已过滤窗口的第二个元素。
在科特林:
fun getAllAfterInsertions() {
getAll()
.startWith(emptyList()) // (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)
}
这是正确的,很抱歉花了这么长时间回复。 您介意解释一下窗口功能如何过滤掉插入内容吗?
要删除而无需通知,我只需替换
MyDao().delete()
一个执行@Query
MyDao().deleteLast()
那么the Flowable不会发出新事件。 @Dao看起来像这样
@Dao
abstract class MyDao : BaseDao {
@Query("DELETE FROM Data WHERE id = (select min(id) from Data)") // or something else
abstract fun deleteLast()
@Delete
fun delete(data: Data)
}
更多推荐
所有评论(0)