Implementing the repository

Repository class is the bridge between the Room database and the ViewModel. This provides data from multiple data sources and isolates the data layer. 

We can separate this repository into two sections; one is DAO, which is mainly used for the local database and to connect the local database with the application. Another section is the network, which is mainly used for handling and communicating between the cloud and application.

Now create a repository class named UsersRepository.kt and declare UserDAO as the constructor of this class.

Here is the code of UsersRepository.kt:

class UsersRepository(private val mUserDAO: UserDAO) {

val mAllUsers: LiveData<List<Users>> = mUserDAO.getAllUsers()

@WorkerThread
suspend fun insert(user: Users){
mUserDAO.addNewUser(user)
}
}

Here, we have initialized the user list. Now the Room will execute all queries. The queries will be done in a different thread.

LiveData will notify the callback function if there are any changes in the database. The insert(user: Users) is the function that is used to wrap the addNewUser(). This insert function has to run on a non-UI thread or the application will crash. To avoid this, we need to use @WorkerThread annotation, which helps to execute this function on a non-UI thread. 

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.144.15.43