Skip to content

Instantly share code, notes, and snippets.

@groue
Last active April 29, 2025 12:19
Show Gist options
  • Save groue/28369e1d99319c90dea5fb8cd305cb39 to your computer and use it in GitHub Desktop.
Save groue/28369e1d99319c90dea5fb8cd305cb39 to your computer and use it in GitHub Desktop.
WithBindable
// Copyright (C) 2024 Gwendal Roué
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
// IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
// CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
// TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
import SwiftUI
/// A property wrapper type that instantiates an observable object.
///
/// It's like `@State`, except that just like `@StateObject` its
/// initializer accepts an autoclosure so that a single instance of the
/// observable object is created for the whole lifetime of the view.
///
/// For example:
///
/// ```swift
/// @Observable MyModel {
/// init() { ... }
/// }
///
/// struct MyView: View {
/// @ObservableState var myModel = MyModel()
///
/// var body: some View { ... }
/// }
/// ```
@propertyWrapper @MainActor
struct ObservableState<Value: AnyObject & Observable>: DynamicProperty {
@StateObject private var container = ValueContainer<Value>()
let makeValue: () -> Value
init(wrappedValue: @autoclosure @escaping () -> Value) {
self.makeValue = wrappedValue
}
var wrappedValue: Value {
container.value ?? makeValue()
}
var projectedValue: Bindable<Value> {
Bindable(wrappedValue)
}
nonisolated func update() {
MainActor.assumeIsolated {
if container.value == nil {
container.value = makeValue()
}
}
}
}
/// Supplies an observable object to a view’s hierarchy.
///
/// The purpose of `WithBindable` is to make it possible to instantiate
/// observable objects from environment values, while keeping the object
/// alive as long as the view is rendered.
///
/// For example:
///
/// ```swift
/// @Observable MyModel {
/// init(myService: Service) { ... }
/// }
///
/// struct MyView: View {
/// @Environment(\.myService) var myService
///
/// var body: some View {
/// WithBindable {
/// MyModel(myService: myService)
/// } content: { myModel in
/// ContentView(myModel: myModel)
/// }
/// }
/// }
///
/// private struct ContentView: View {
/// @Bindable var myModel: MyModel
///
/// var body: some View { ... }
/// }
/// ```
///
/// `WithBindable` makes sure a single instance of the observable object
/// is created for the whole lifetime of the view. It is thus possible to
/// perform work from the object initializer.
struct WithBindable<Value: AnyObject & Observable, Content: View>: View {
@ObservableState var state: Value
private let content: (Value) -> Content
init(
_ makeValue: @escaping () -> Value,
@ViewBuilder content: @escaping (Value) -> Content)
{
self._state = ObservableState(wrappedValue: makeValue())
self.content = content
}
var body: some View {
content(state)
}
}
/// The object that is instantiated once with `@StateObject` and takes care
/// of the lifetime of the value.
private final class ValueContainer<Value: Observable>: ObservableObject {
// No need to make it @Published because Value is Observable.
var value: Value?
}
// MARK: - Preview
#if DEBUG
@Observable @MainActor
private final class DemoModel {
static var instanceCount = 0
var text: String
init() {
// Preview crashes if DemoModel is instantiated more than once.
// This helps asserting the desired behavior of the preview, which
// is that not more than two instances are created.
precondition(DemoModel.instanceCount < 2)
DemoModel.instanceCount += 1
self.text = ""
}
}
#Preview {
struct ContainerView: View {
@State var counter: Int = 1
var body: some View {
Form {
Section {
Text(verbatim: "Container body rendered \(counter) times")
.contentTransition(.numericText())
.animation(.default, value: counter)
} header: {
Text(verbatim: "Container View")
}
Section {
ContentView1()
} header: {
Text(verbatim: "@ObservableState demo")
}
Section {
WithBindable {
DemoModel()
} content: { model in
ContentView2(model: model)
}
} header: {
Text(verbatim: "WithBindable demo")
}
Button {
counter += 1
} label: {
Text(verbatim: "Force container body re-evaluation")
}
}
.headerProminence(.increased)
}
}
// ObservableState demo
struct ContentView1: View {
@ObservableState var model = DemoModel()
var body: some View {
TextField("", text: $model.text, prompt: Text(verbatim: "Enter text here"))
WitnessView(model: model)
}
}
// WithBindable demo
struct ContentView2: View {
@Bindable var model: DemoModel
var body: some View {
TextField("", text: $model.text, prompt: Text(verbatim: "Enter text here"))
WitnessView(model: model)
}
}
// Must update when model changes.
struct WitnessView: View {
var model: DemoModel
var body: some View {
Text(verbatim: "Model.text is '\(model.text)'")
}
}
return ContainerView()
}
#endif
@paskowski
Copy link

Thank you for this snippet, it has helped us tremendously while migrating to @observable.
Could you explain how can we be sure that function below will always be called from MainActor - or to put it differently that it will in fact always be isolated on MainActor even though it's nonisolated?

nonisolated func update() {
        MainActor.assumeIsolated {
            if container.value == nil {
                container.value = makeValue()
            }
        }
    }

@groue
Copy link
Author

groue commented Apr 29, 2025

Hi @paskowski.

Could you explain how can we be sure that function below will always be called from MainActor - or to put it differently that it will in fact always be isolated on MainActor even though it's nonisolated?

DynamicProperty.update is not marked @MainActor, so there is no way to be sure. Hence the use of MainActor.assumeIsolated, that crashes whenever this assumption turns wrong at runtime. I've never seen SwiftUI call it outside of the main actor, though.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment