I use MVVM architecture with Room DB and LiveData in my project. When the application works offline, the data is received from roomdb, and when the user is connected to the Internet, when entering the application, the data is received as Livedata from roomdb and a request is sent to the server to update the Room DB and update the observed list with Livedata.
I did the update as follows in the repository constructor:
public MainRepository(Application application) {
DatabaseManager databaseManager = DatabaseManager.getInstance(application);
dataDao = databaseManager.dataDao();
context = application.getApplicationContext();
getDataFromWebService();
}
Inside the getDataFromWebService()
function, I retrofit the data from the server and place it asynctask on the server with OnConflictStrategy.REPLACE.
Now when the app opens, I receive and display the data with the observer.
My problem is that in this case, the data is fetched twice, but when I remove the getDataFromWebService()
function from the code above, it fetches only once correctly.
Twice fetching the list has exactly the same data but the list is updated again and the animation corrupts the display of data.
Please help me how to update the database without fetching the list twice.
Is updating the database in the repository constructor correct? If not, then where should the update be done?