Observable Architecture: Observing Optionals

Episode #261 • Dec 11, 2023 • Subscriber-Only

The Composable Architecture can now observe struct state, but it requires a lot of boilerplate. Let’s fix this by leveraging the @Observable macro from the Swift open source repository. And let’s explore what it means to observe optional state and eliminate the library’s IfLetStore view for a simple if let statement.

Previous episode
Observable Architecture: Observing Optionals
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

Brandon

We now have the very basics of support for Swift’s observation machinery in the Composable Architecture. Now we have barely scratched the surface so far, but we have overcome some of its biggest technical hurdles.

We have introduced the notion of identity for the state of our features, even though the state is a value type. That notion of identity gives us the ability to distinguish between when a piece of state is wholesale replace or simply mutated in place. And that is precisely what allows our views to observe only the state that the view touches, even though we are dealing with value types at every layer.

We saw previously that was basically impossible in vanilla SwiftUI due to the complications of value types, but because the Composable Architecture is a far more constrained system with a single reference type at its core, we are able to pull it off. And it’s pretty incredible.

Stephen

But right now we have a bunch of code written that no one is ever going to want to write themselves. It’s very similar to the code that the @Observable macro writes for us when building vanilla SwiftUI applications, but there are a few tweaks we made, but also that macro is prohibited from being applied to structs.

So, it sounds like we need need our own macro that can write all of this code for us. And luckily for us the @Observable macro is a part of Swift’s open source project, and so we can basically copy-and-paste their macro over to our project, and make a few small tweaks.

Let’s give it a shot.

The @ObservableState macro


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