Is there any good pattern for keeping track of the...
# android
j
Is there any good pattern for keeping track of the latest value of a DataStore preference without having to go via Flow and asynchronicity, for example for keeping track of a boolean value at various places without having to go through coroutines? Like observing all changes and updating a property which can be used in if/else in various parts of the code base? Code examples? Or is it a bad idea altogether?
i
Seems like that's a recipe for either out of date information or confusion over which value is the actual source of truth. Calling
first()
on the Flow when you need it avoids those issues
c
A StateFlow is the coroutine option for retaining the latest value. An
Observable
delegated property might be what you’re looking for in a non-coroutines option https://kotlinlang.org/docs/reference/delegated-properties.html#observable
j
@Ian Lake I understand that single source of truth is important but was thinking of something like a cache which would stay in sync all the time. Since
first()
is a suspend fun I would have to use coroutines everywhere I want to check that value, right? If I want to return a value from a function which uses logic based on a setting I would have to convert the function to use coroutines or a take in a callback right?
i
You would make it a
suspend
method, yes
👍 1
j
@Casey Brooks I've thought about those things but don't see an obvious way to do it since afaik delegated properties don't support suspend and it's not obvious to me how I would update the StateFlow from the DataStore flow. I guess using coroutines everywhere I want to check the value is the way to go.
c
I was meaning StateFlow and Observable delegates as two separate solutions, not to use them together. If you use an
Observable
delegated property for that boolean flag, you can be notified on any changes to that property and push that change out to a list of listeners (I think you’d have to manage the list of subscribers manually, but it’s pretty trivial). Using and Observable property, you wouldn’t need to use coroutines
j
But still DataStore uses Flow and all functions like first() to get a value from Flow are
suspend
which need to be invoked in a coroutine. Let's say the user has a setting like for example useAmPm true/false. Then in a method where I want to return formatted time I would have to be in a coroutine or launch a coroutine unless I have a coroutine running somewhere updating a property which doesn't seem recommended. Anyway I appreciate the suggestions.
c
Ah, my bad. I didn’t realize DataStore itself is based on Flows
👌 1
👍 1