Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to observe optional ObservableObject in SwiftUI #988

Open
onmyway133 opened this issue Dec 18, 2024 · 0 comments
Open

How to observe optional ObservableObject in SwiftUI #988

onmyway133 opened this issue Dec 18, 2024 · 0 comments

Comments

@onmyway133
Copy link
Owner

onmyway133 commented Dec 18, 2024

When working with Core Data, there are times we have optional NSManagedObject to pass around. These objects conform to ObservableObject, and in SwiftUI we can't @ObservedObject on optional ObservableObject

One way we can workaround this is to introduce a wrapper type that checks and internally observes the ObservableObject

struct ObserveView<T: ObservableObject, Content: View>: View {
    var object: T?
    @ViewBuilder var content: (T) -> Content
    
    struct InnerView: View {
        @ObservedObject var object: T
        var content: (T) -> Content
        
        var body: some View {
            content(object)
        }
    }
    
    var body: some View {
        if let object {
            InnerView(object: object, content: content)
        }
    }
}

@ViewBuilder
func observe<T: ObservableObject, Content: View>(_ object: T?, @ViewBuilder content: @escaping (T) -> Content) -> some View {
    ObserveView(object: object, content: content)
}

So we can use like

var book: Book?

observe(book) { book in
    Text(book.name)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant