Is It Possible To Read/write Primitive Types From Datastore Without Flows?
Solution 1:
In terms of writing, flows are not used. You can save a primitive as it outlines in the documentation and unless you specify otherwise, this will be done on a background thread.
For reading, DataStore
only returns a flow for a reason. As @CommonsWare said in the comments: "Reading values may require disk or other forms of I/O, so they elected to implement a reactive API, so that I/O can be performed on a background thread."
By using a suspend function you can just return an Int
as you described by using the first()
terminal operator on the flow, which returns the first value emitted.
suspendfunread(): Int {
return dataStore.data.first()[KEY] ?: DEFAULT_VALUE
}
If you really need the call to be synchronous then you can block the thread using runBlocking
in combination with first()
, however as they warn in the documentation:
Avoid blocking threads on DataStore data reads whenever possible. Blocking the UI thread can cause ANRs or UI jank, and blocking other threads can result in deadlock.
so if this is necessary, there's probably an issue with the general design of your app.
Post a Comment for "Is It Possible To Read/write Primitive Types From Datastore Without Flows?"