privatevoidsubscribeUi(LiveData<List<ProductEntity>> liveData){ // Update the list when the data changes liveData.observe(getViewLifecycleOwner(), myProducts -> { if (myProducts != null) { mBinding.setIsLoading(false); mProductAdapter.setProductList(myProducts); } else { mBinding.setIsLoading(true); } // espresso does not know how to wait for data binding's loop so we execute changes sync. mBinding.executePendingBindings(); }); } /*@Override public void onDestroyView()*/ privatefinal ProductClickCallback mProductClickCallback = product -> { if (getLifecycle().getCurrentState().isAtLeast(Lifecycle.State.STARTED)) { ((MainActivity) requireActivity()).show(product); } }; }
// Use the savedStateHandle.getLiveData() as the input to switchMap, // allowing us to recalculate what LiveData to get from the DataRepository // based on what query the user has entered mProducts = Transformations.switchMap( savedStateHandle.getLiveData("QUERY", null), (Function<CharSequence, LiveData<List<ProductEntity>>>) query -> { if (TextUtils.isEmpty(query)) { return mRepository.getProducts(); } return mRepository.searchProducts("*" + query + "*"); }); } publicvoidsetQuery(CharSequence query){ // Save the user's query into the SavedStateHandle. // This ensures that we retain the value across process death // and is used as the input into the Transformations.switchMap above mSavedStateHandler.set(QUERY_KEY, query); } /** * Expose the LiveData Products query so the UI can observe it. */ public LiveData<List<ProductEntity>> getProducts() { return mProducts; } }
publicstatic DataRepository getInstance(final AppDatabase database){ if (sInstance == null) { synchronized (DataRepository.class) { if (sInstance == null) { sInstance = new DataRepository(database); } } } return sInstance; }
/** * Get the list of products from the database and get notified when the data changes. */ public LiveData<List<ProductEntity>> getProducts() { return mObservableProducts; }
public LiveData<ProductEntity> loadProduct(finalint productId){ return mDatabase.productDao().loadProduct(productId); }
public LiveData<List<CommentEntity>> loadComments(finalint productId) { return mDatabase.commentDao().loadComments(productId); }
public LiveData<List<ProductEntity>> searchProducts(String query) { return mDatabase.productDao().searchAllProducts(query); } }
/** * Build the database. {@link Builder#build()} only sets up the database configuration and * creates a new instance of the database. * The SQLite database is only created when it's accessed for the first time. */ privatestatic AppDatabase buildDatabase(final Context appContext, final AppExecutors executors){ return Room.databaseBuilder(appContext, AppDatabase.class, DATABASE_NAME) .addCallback(new Callback() { @Override publicvoidonCreate(@NonNull SupportSQLiteDatabase db){ super.onCreate(db); executors.diskIO().execute(() -> { // Add a delay to simulate a long-running operation addDelay(); // Generate the data for pre-population AppDatabase database = AppDatabase.getInstance(appContext, executors); List<ProductEntity> products = DataGenerator.generateProducts(); List<CommentEntity> comments = DataGenerator.generateCommentsForProducts(products);
insertData(database, products, comments); // notify that the database was created and it's ready to be used database.setDatabaseCreated(); }); } }) .addMigrations(MIGRATION_1_2) .build(); }
/** * Check whether the database already exists and expose it via {@link #getDatabaseCreated()} */ privatevoidupdateDatabaseCreated(final Context context) privatevoidsetDatabaseCreated(){ mIsDatabaseCreated.postValue(true); }
privatestaticvoidinsertData(final AppDatabase database, final List<ProductEntity> products, final List<CommentEntity> comments){ database.runInTransaction(() -> { database.productDao().insertAll(products); database.commentDao().insertAll(comments); }); } privatestaticvoidaddDelay()// Thread.sleep(4000); // public LiveData<Boolean> getDatabaseCreated() // private static final Migration MIGRATION_1_2 = new Migration(1, 2) { }; }
DAO
@Dao publicinterfaceProductDao{ @Query("SELECT * FROM products") LiveData<List<ProductEntity>> loadAllProducts();