How to integrate Room database with other Android components?

Integrating Room database with other Android components allows for efficient data persistence and retrieval in applications. Room provides a robust solution for managing data, enabling smoother interaction between UI components, ViewModels, and repositories.
Room database, Android components, ViewModel, LiveData, Repository pattern

Example of Integrating Room with ViewModel and LiveData

// Entities @Entity(tableName = "users") public class User { @PrimaryKey(autoGenerate = true) private int id; private String name; // Getters and Setters } // DAO @Dao public interface UserDao { @Insert void insert(User user); @Query("SELECT * FROM users") LiveData> getAllUsers(); } // Database @Database(entities = {User.class}, version = 1) public abstract class AppDatabase extends RoomDatabase { public abstract UserDao userDao(); } // Repository public class UserRepository { private UserDao userDao; private LiveData> allUsers; public UserRepository(Application application) { AppDatabase db = Room.databaseBuilder(application, AppDatabase.class, "database-name").build(); userDao = db.userDao(); allUsers = userDao.getAllUsers(); } public LiveData> getAllUsers() { return allUsers; } public void insert(User user) { new InsertAsyncTask(userDao).execute(user); } private static class InsertAsyncTask extends AsyncTask { private UserDao asyncTaskDao; InsertAsyncTask(UserDao dao) { asyncTaskDao = dao; } @Override protected Void doInBackground(final User... params) { asyncTaskDao.insert(params[0]); return null; } } } // ViewModel public class UserViewModel extends AndroidViewModel { private UserRepository repository; private LiveData> allUsers; public UserViewModel(Application application) { super(application); repository = new UserRepository(application); allUsers = repository.getAllUsers(); } LiveData> getAllUsers() { return allUsers; } public void insert(User user) { repository.insert(user); } }

Room database Android components ViewModel LiveData Repository pattern