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
  • 41,901
  • 18
  • 127
  • 145
Tommehh
  • 872
  • 1
  • 17
  • 44

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,388
  • 1
  • 27
  • 50
  • 1
    so why is there a function like "commit()"? – Tommehh Dec 15 '17 at 09:40
  • 2
    commit is useful if you need to know if the write was successful or not. If you don't use that information, always use apply – Tim Dec 15 '17 at 09:42
  • 1
    `commit()` was present in the original API level 1, `apply()` was introduced in API level 9. `commit()` returns `true` if the write to disk operation succeeded, while with `apply()` you have to hope for the best. – Xavier Rubio Jansana Dec 15 '17 at 09:43
  • Very informatif comment. Thanks @Tim – nandur Sep 11 '20 at 03:26
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
  • 4,393
  • 3
  • 21
  • 37