DEV Community

HarmonyOS
HarmonyOS

Posted on

Ensuring Persistent Key Deletion in HarmonyOS: Using dataPreferences.Preferences with flushSync

Read the original article:Ensuring Persistent Key Deletion in HarmonyOS: Using dataPreferences.Preferences with flushSync

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

  1. Reproduced the issue by calling deleteSync() followed by an immediate app exit.
  2. Verified that on relaunch, the supposedly deleted key was still accessible.
  3. Checked HarmonyOS documentation and found that persistence requires calling flushSync() or flush() explicitly.
  4. Modified the code to add flushSync() after deleteSync().

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}`);
}
Enter fullscreen mode Exit fullscreen mode
  • Always call flushSync() (or await 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.

Related Documents or Links

Written by Bunyamin Eymen Alagoz

Top comments (0)