Search code examples
androidrx-javaandroid-roomrx-androidandroid-diffutils

Android Room - how to get the new data only?


What is a result of this Dao method after inserting some messages in the database:

@Query("SELECT * FROM messages")
Flowable<List<Message>> getMessages();

1 - ALL messages stored in the database will be emitted after this change

or

2 - Only the DIFFERENCE beetwen new and old messages will be emitted after the change?

In which documents is it specified? If first, what should I do to get the difference - something like DiffUtils or there are other approaches?

P.S. What if I DELETE some messages?


Solution

    1. All the messages stored in the database will be emitted.
    2. To get the difference, the recommended approach is to use DiffUtils as you mentioned. There is a lot of information about how it works and how to implement it. Just to mention a few here you have this Mindorks' tutorial and @iammert tutorial
    3. You can write a different query if you don't want to get all the messages every time some of them change. This depends on your use case but, for example, you can have a query that returns all the messages after a certain date if you know that older messages will not change.
    4. If you the delete some messages, the result of the query will change. Therefore, you will have all the messages emitted again.
    5. I would use LiveData<List<Message>> instead. The behavior is the same and you don't need to worry about disposing your subscriptions, nor worry about configuration changes. However, I would use Single or Maybe when you have to return a single result.

    Update: instead of getting all the messages and seeing the difference between them using DiffUtils, you can retrieve a subset of the messages and update it on demand. The new Paging library in Android helps you doing this. Again, there is a lot of information around about how to do this so I am not going to put the details of the implementation here because it is out of the scope of the question, but here you have one of the many tutorials available.