3

I know the difference between apply and commit. In my case I would like to use commit(), but android suggests me to use apply() because it runs in background and doesn't block the main thread.

Does something like this work if I use apply or is it possible that apply did not update it before calling?

editor.putBoolean("TEST", true)
editor.apply()

if (preferences.getBoolean("TEST")) {
   //do something
}
Tim
  • 39,651
  • 17
  • 123
  • 137
Thomas Klammer
  • 782
  • 1
  • 11
  • 34

2 Answers2

12

I would expect it to work, as in the documentation it states:

apply() commits its changes to the in-memory SharedPreferences immediately but starts an asynchronous commit to disk and you won't be notified of any failures.

As you're accessing the same preferences object (is a singleton) you should see a consistent view at all times.

Xavier Rubio Jansana
  • 6,218
  • 1
  • 25
  • 46
4

apply() writes to a temporary Map that is later written asynchronously to disk. If you immediately use methods like getBoolean() in your case, it will first lookup if there is a value for this key in the temporary Map and returns it.

Check the source code of SharedPreferencesImpl to see exactly how it's working.

ElegyD
  • 3,913
  • 3
  • 21
  • 36