Skip to content

Instantly share code, notes, and snippets.

@greenrobot
Created March 26, 2018 15:23
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save greenrobot/5078a4c86f4fadc5c25711b0a90ecf3a to your computer and use it in GitHub Desktop.
Save greenrobot/5078a4c86f4fadc5c25711b0a90ecf3a to your computer and use it in GitHub Desktop.
A "rescue" version of Box.removeAll() for DBs that reached their size limit.
/**
* A "rescue" version of Box.removeAll() for DBs that reached their size limit.
* Removes data in multiple transactions of increasing size to minimize required additional disk space.
* <p>
* Note that this method is not transactional, so it might fail in between, with any number of objects removed.
* Thus, you should persistently track the state yourself, e.g. by setting a SharedPreferences flag to indicate
* that removal is in progress. If this methods fails, you can check this flag to retry at a later point.
* Only once this method succeeds, this flag should be cleared.
* <p>
* It's recommended to increase the max. DB size to ensure addition capacity is available for this method.
*/
private void removeAllMultiTx(Box box) {
int removeCount = 1;
Query query = box.query().build();
int opsForRemoveCount = 0;
Log.i("ObjectBox", "Starting clean...");
Log.i("ObjectBox", "Initial count: " + box.count());
long removedSum = 0;
while (true) {
List toRemove = query.find(0, removeCount);
if (toRemove.isEmpty()) {
Log.i("ObjectBox", "Done, count: " + box.count());
break;
}
// Log.i("ObjectBox", "Before remove:\n" + CallAppApplication.boxStore.diagnose());
Collections.reverse(toRemove);
box.remove(toRemove);
removedSum += toRemove.size();
// Log.i("ObjectBox", "After remove:\n" + CallAppApplication.boxStore.diagnose());
opsForRemoveCount++;
if (opsForRemoveCount == 4) {
// Delete 4 * removeCount entities, before doubling removeCount:
// 1) minimize required additional space (starting with removeCount = 1)
// 2) increase likeliness that enough free pages are available as removeCount grows
removeCount = Math.min(10000, removeCount * 2);
opsForRemoveCount = 0;
Log.i("ObjectBox", "Removed: " + removedSum);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment