Drop delete trigger for Room database

故事扮演 提交于 2019-12-06 17:43:24

You can get a Flowable<List<Comment>> that only emits on insertions and not on deletions by filtering the original getAll() Flowable so that only those List<Comment> items are passed through that contain more Comments than the previous List<Comment>.

You can implement this filtering with the following transformations:

  1. Prepend the flowable with an empty list so that we have a baseline for insertions.
  2. Get RxJava window()s of size 2, so that we will be able to compare adjacent items.
  3. window() returns Flowable<Flowable<Comment>>. Convert it to Flowable<List<Comment>> with flatMap() and toList() on the inner Flowable.
  4. Filter those 2-element windows that represent an insertion (the size of the first element is less than the size of the second).
  5. Emit only the 2nd element of the filtered windows.

In 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)
}

To delete without notification I simply replace

MyDao().delete()

with one executing a @Query

MyDao().deleteLast()

then thew Flowable doesn't emit a new event. The @Dao looks like this

@Dao
abstract class MyDao : BaseDao<Data> {

   @Query("DELETE FROM Data WHERE id = (select min(id) from Data)") // or something else
   abstract fun deleteLast()

   @Delete
   fun delete(data: Data)

}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!