Search code examples
androidandroid-roomandroid-architecture-components

Android Architecture Components - Remove old data from room


Currently I'm working on Android app architecture, i can't understand one thing in Github Repo Sample; We can decide to fetch new data using rate limiter or null checking, but in this case we just insert new values in to database, we are not deleting old values from database. For example what if one of the old results in database removed from server (user deleted repo) ? It will be still in database? How can we eliminate this values? Am i missing something or is this an unhandled case?


Solution

  • I think I have an optimized and simpler solution. Please, help make it even simpler!

    // Dao class
    
    @Dao
    public interface UserDao {
        // ...    
    
        @Insert(onConflict = OnConflictStrategy.REPLACE)
        void insertAll(List<User> users);
    
        @Query("DELETE FROM User WHERE User.id NOT IN(:lstIDUsers)")
        void deleteOldUsers(List<Integer> lstIDUsers);
    }  
    

    // File that calls Dao - example: Repository class)

    // First, convert and add all Json data to lstUsers
    
    // Second, add only Json primary key elements 
    // from lstUsers to a new list lstIDUsers
    
    userDao.insertAll(lstUsers);
    userDao.deleteOldUsers(lstIDUsers);
    

    These two commands first insert all elements with OnConflictStrategy.REPLACE, and after delete only old elements removed from remote or local DB.