I'm using preferences datastore (sharedpref replac...
# android
c
I'm using preferences datastore (sharedpref replacement) and it only seems to support a Flow and it doesn't support a synchrounous api. I have an app setting that has to be read super early in the app (basically it's the first thing that has to be read in the app for initialization). Is there an easy way to do this with datastore, or should I just look up how to convert a Flow into a synchronous single call?
c
Damn. And here I was looking at the getting started codelab
c
The CodeLabs can sometimes fall out-of-date, the official documentation at developer.android.com is usually pretty thorough for the latest Jetpack features, and will typically be the most up-to-date. It's always a good idea to look there first for your answer. That said, the snippet shown in the Datastore documentation is just normal Kotlin coroutines stuff.
runBlocking
is part of the core coroutines library on JVM/Android, and is a useful tool for anytime you have a coroutines-based API that needs to be used in a synchronous context. You need to really be careful with it and know what you're doing though, as it can very easily lead to slow or unresponsive UI if abused.
👍 1
Also note that the Codelabs are not intended to be feature-complete documentation; they're guided lessons for the most-used features, but gloss over a lot of the other details or features available in these libraries. Another reason to prefer the official documentation over the CodeLabs
c
yeah. duckduckgo just sucks apparently
f
if you need to wait for something before starting your app, you can consider the technique described in the splash screen docs, have an
onPredrawListener
that returns
false
until whatever needs to take place has completed, in this case, reading your value from datastore. This way you can read it on a background thread and the app is responsive (albeit just showing the splash logo or animation), rather than blocking the main thread https://developer.android.com/guide/topics/ui/splash-screen#suspend-drawing
not supported synchronous APIs in intentional, to avoid people shooting themselves in the foot by blocking the main thread