'How to return value from DataStore in non-suspend function
I was saving app language in shared preferences and set the app language by overriding attachBaseContext() in activity like the following:
override fun attachBaseContext(base: Context) {
val language: String = sharedPreferences.language
super.attachBaseContext(wrapContext(base, language))
}
where wrapContext() is a function change the language based on its parameter value.
after migration to DataStore, I can't return the language in attachBaseContext() since it's not suspend function, and language become a flow (should collect inside a suspend function)
How can I solve this problem?
Solution 1:[1]
DataStore is asynchronous API for writing and reading small amounts of data. To read data synchronously you need to use runBlocking coroutine builder. This will block the calling thread until DataStore returns that can lead to ANRs:
val syncData = runBlocking { context.dataStore.data.first() } // or { context.dataStore.data.firstOrNull() }
It is a good chance to think about how you can use DataStore asynchronously without runBlocking, maybe do some refactoring.
If you decide to use runBlocking you need to think about reasonable timeout to not freeze UI forever:
val syncData = runBlocking {
withTimeoutOrNull(2000) { // UI can freeze for 2 seconds
context.dataStore.data.first()
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | BigSt |
