Shared State: User Defaults, Part 2

Episode #274 • Apr 8, 2024 • Subscriber-Only

We can now persist simple bits of state to user defaults using the @Shared property wrapper, but there is more work to be done. We need to observe changes to user defaults in order to play those changes back to @Shared, and we need to put in a bit of extra work to make everything testable.

Previous episode
Shared State: User Defaults, Part 2
Next episode
Locked

Unlock This Episode

Our Free plan includes 1 subscriber-only episode of your choice, plus weekly updates from our newsletter.

Sign in with GitHub

Introduction

Stephen

Currently the shared state is not listening for changes to the user defaults that happens externally so that it can update itself accordingly. This is the same problem we saw with holding onto @AppStorage in an @Observable object. It could clearly load from and save to user defaults, but it didn’t observe changes made to user defaults from other parts of the application.

Brandon

But unlike that situation, we can actually fix it for our @Shared property wrapper. We can beef up the PersistenceKey protocol so that conformers to it are capable of describing updates to the value that happen in the external system, such as user defaults or the file system, and then the Storage type can use that information to update its currentValue accordingly.

Let’s see what it takes.

External updates


Downloads

Get started with our free plan

Our free plan includes 1 subscriber-only episode of your choice, access to 62 free episodes with transcripts and code samples, and weekly updates from our newsletter.

View plans and pricing