Android Sqlite Multi Threading Save Data With Dbflow + Retrofit
Solution 1:
What you are doing here is the first "dont' do" in the docs of DBFlow. What you should use here is a transaction to store the data. This locks the database for an exclusive batch operation and should be a lot faster than iterating over all you models and save them one by one.
Basically, you want to use FastStoreModelTransaction.saveBuilder()
here which basically does a INSERT OR UPDATE
.
Usage would be like that:
publicvoidonResponse(Call<AdminPictures> call, Response<AdminPictures> response) {
AdminPicturesapResponse= response.body();
final List<PictureInfos> pictureInfos = apResponse.getPicturesList();
FastStoreModelTransactiontransaction= FastStoreModelTransaction.saveBuilder(FlowManager.getModelAdapter(PictureInfos.class))
.addAll(pictureInfos)
.build();
database.executeTransaction(transaction);
}
Please note that this would automatically runs in the background, so no need to wrap it in an extra thread. If you need a listener on the storing process, use the ProcessModelTransaction
instead.
Solution 2:
Reading database can be done in parallel without interrupting each other, but writing in to database should be done in a synchronized way if you have keys.
You should write the save
within a synchronized method. Synchronize will allow only one thread to do changes at a time.
Note:
By default android SQLiteDatabase
Object is safe for multithreading. DBFlow
is also. Make sure you are using the same instances of helpers in multiple threads.
Post a Comment for "Android Sqlite Multi Threading Save Data With Dbflow + Retrofit"