Ensuring Persistent Key Deletion in HarmonyOS: Using dataPreferences.Preferences with flushSync
Problem Description
When using the dataPreferences.Preferences.deleteSync() API to remove a stored key, the deletion seems successful. However, if the application process is immediately terminated and restarted, the same key may still return the old value, indicating that the deletion was not persisted.
Background Knowledge
The dataPreferences.Preferences API provides a key-value storage mechanism for HarmonyOS applications.
-
deleteSync()only updates the data in memory. - Without an explicit flush operation, changes may not be persisted to disk before the process ends.
- As a result, deleted keys may reappear when the app restarts.
Troubleshooting Process
- Reproduced the issue by calling
deleteSync()followed by an immediate app exit. - Verified that on relaunch, the supposedly deleted key was still accessible.
- Checked HarmonyOS documentation and found that persistence requires calling
flushSync()orflush()explicitly. - Modified the code to add
flushSync()afterdeleteSync().
Analysis Conclusion
The root cause of the issue is that deleteSync() alone does not guarantee persistence. Without flushing, changes remain in memory and are lost when the process exits.
Solution
Update the code to ensure persistence after deletion:
try {
preferences!.deleteSync(key);
preferences!.flushSync(); // Force data persistence
} catch (err) {
let code = (err as BusinessError).code;
let message = (err as BusinessError).message;
console.error(`Failed to delete key '${key}'. Code: ${code}, message: ${message}`);
}
- Always call
flushSync()(orawait flush()) after delete/update operations if the app may terminate soon. - This guarantees the data is written to persistent storage.
Verification Result
After adding flushSync(), the deleted key no longer reappears when the application is closed and reopened. The issue has been verified on multiple devices running HarmonyOS 5.0.0.
Top comments (0)