Flow not updating on SharedPreferences value change
See original GitHub issueI’m having an issue where after the initial value my Flows aren’t updating when a new value is saved in SharedPreferences.
I’ve linked to a project that reproduces it but the gist is:
val myPref: Preference<Int> = preferences.getInt(MY_PREF_KEY)
update_pref.setOnClickListener {
val selection = (0..2).random()
GlobalScope.launch { myPref.setAndCommit(selection) }
}
myPref.asFlow()
// This doesn't get triggered after the initial value
.onEach { Log.d(tag, "PREF CHANGE: $it") }
.launchIn(GlobalScope)
Issue Analytics
- State:
- Created 3 years ago
- Comments:8 (6 by maintainers)
Top Results From Across the Web
Android Preferences DataStore Flow Doesn't Emit Same Value
Each time you want to update data, you first compare the new value with the previous one. And if data is the same,...
Read more >SharedPreferences.OnSharedPreferenceChangeListener
Called when a shared preference is changed, added, or removed. This may be called even if a preference is set to its existing...
Read more >All about Preferences DataStore - Medium
In this post, we will take a look at Preferences DataStore, one of two DataStore implementations. We will go over how to create...
Read more >Is Jetpack DataStore a replacement for SharedPreferences?
It was built using Kotlin coroutines and Flow to store data asynchronously, consistently, and transactionally. There are two ways of ...
Read more >Listening for preference value change | Android Studio
SharedPreferences Change Listener Android | Listening for preference ... https://youtu.be/TsASX0ZK9ak ◀️ Delete shared preferences data ...
Read more >
Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free
Top Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
I also had this problem and I’ve traced that it’s connected to the “problem” that my coroutine was probably garbage collected since
SharedPreferences
does not store strong reference to the registeredSharedPreferences.OnSharedPreferenceChangeListener
. My code was something likeI’ve fixed that by storing given Job to the field property
it’s kind of hack/workaround but it helped
Good findings here, but I’m closing this issue as I don’t think this is really related to the library itself.