Android Room persistence library — Using the delegate pattern to update the UI after a database operation

Android Room persistence library — Using the delegate pattern to update the UI after a database operation

5 years ago
Anonymous $fWzGa1uP8i

https://medium.com/@wiltongomesjr/android-room-persistence-library-using-the-delegate-pattern-to-update-the-ui-after-a-database-31475ce158f1

If you are using the room persistence library to handle Sqlite database operations on your android app, you should probably know that the library forces the developer to do all its db calls inside a background thread. So, if you are using the DAO pattern and wants to keep database logic, including the asynchronous executions encapsulated in your DAO classes, you will need to design them in a way that they can notify the calling activity after the background process finishes. After that, UI updates can take place on the main thread.

Now, I will show you how I could achieve this by making using of inner class and delegate pattern. For this example, we will need to write 4 classes and 2 interfaces and I will try to explain the code of the most important portions. Explaining basic Room concepts is not the objective of this article and we are going to focus on the main theme here. Before we can go ahead, I want to make clear that I’m not trying to reinvent the wheel. Some concepts used in this example are well known and I’m just put things together to do what we need. So, let’s go.