Android Observe Shared Preferences as LiveData

İbrahim Süren
AndroidPub
Published in
2 min readJan 1, 2019

--

Android Shared Preferences is best and easy way of the key-value storage. It also provides callback to listen changes in the preference values. However, can we make this use more suitable for our architecture?

Let’s imagine we have an Android application and it storages some feature status data (like open-closed) in the shared preferences. Multiple fragments of application has indicators which are showing that feature status and we want to see changes immediately. Each indicator is getting status of feature from shared preferences. Additionally, this feature status can also be updated in some service or broadcast receiver.

We can use OnSharedPreferenceChangeListener to listen changes in the preferences but as you can see, we have to check every possible key changes in the when statement and we need to register and unregister listener in every fragment we listen in. Additionally, it doesn’t look good and clean. We can do better!

Firstly, we have created two variables, listener to listen changes in the shared preference, and updates to observe this changes. This code block will notify the Observable object on every preference value change.

Secondly, we have created a class LivePreference that extends MutableLiveData. This will allow us to observe it with observer. Later, we have filtered preference value change updates by key and posted them to the superclass. Now we need to write getter methods.

Let’s use them and observe preference values in our activity class.

One more thing, if we need to listen multiple same type preferences in the one lifeCycleOwner, we can create a new class for that too. The only difference is that, we will check our key is exists in the key list instead of checking keys are equal.

We use generics in the function because we can listen any type of preference.

Finally, example usage of function will be like that. We only observe keys and values of bool1, bool2 and bool3 which are boolean.

Thanks for the reading! You can find the repository here, and you can also use it by implementing to your project.

--

--