Shared state with persistence and default values #2956
Replies: 3 comments 3 replies
-
I've uploaded an example app that demonstrates a basic login/logout system where initialising a new logged in state every time a user logs in resets the shared user state. It demonstrates the use of a default-providing key. https://gist.github.com/lukeredpath/2bf827a04a7d25b8482ff475c24ea5ec Thinking more about the logged in only shared state use case, I think one last useful feature would be to have some kind of way of defining a key where default value access triggers a purple warning, for use cases where its only there to satisfy the compiler where you want a non-optional value that should only be available in certain runtime situations, e.g. the user is logged in. Perhaps if the Another useful thing would be an API for clearing persisted shared state - e.g. when a user logs out, you clear the persisted value so any further access of the shared state before the user logs back in would access the default value and once again trigger the purple warning. |
Beta Was this translation helpful? Give feedback.
-
I enthusiastically second this. I tried to implement something like it as a static extension on the Shared type, but couldn't figure it out. Decorating the PersistenceKey makes a lot of sense to me. |
Beta Was this translation helpful? Give feedback.
-
I'm happy to turn this into a proper PR with additional helpers and tests if others think this would be useful. @mbrandonw would you be happy to review a PR on this into the |
Beta Was this translation helpful? Give feedback.
-
After finally playing around with the shared state beta, one thing I found inconvenient was having to provide a default value everywhere when using a persistence strategy. It felt like it should be possible to define a default value once, when defining the persistence key.
I had a go at implementing this myself:
shared-state-beta...lukeredpath:swift-composable-architecture:lukeredpath/default-providing-key
This branch adds a new generic persistence key,
DefaultValueProviding<Key>
that effectively decorates any otherSendable
andHashable
conforming persistence key but also holds onto a default value - one caveat is that theValue
type itself must beHashable
andSendable
in order for the wrapper key to conform to these protocols.As an example I've provided a single convenience method for creating an
inMemory
key with a default value - other conveniences could be added for other key types.A single new overload on
ValueReference
provides a way to initialise a persisted shared state where it will fall back to the default value if nothing is currently persisted:Would this be a useful addition? Because it requires the additional overload on
ValueReference
I'm not sure it could be implemented in your own codebase.Beta Was this translation helpful? Give feedback.
All reactions