Alejandro Ciniglio

Wrapper view to unwrap observable objects

I have a list of ObservableObjects and an editing view that should let me edit them one at a time. I’m using an NSSplitViewController, so the list view and the editing view don’t share a SwiftUI ancestor.

I ended up using a PassthroughSubject to publish the selected item, and then the editing view has an onReceive on that publisher.

I ran into an issue with how to actually pass the fields of that item to SwiftUI views (e.g. TextField). To work around this, I made an intermediary wrapper view, that recieves the updated item, sets it to it’s own state, and then passes that as an @ObservedObject to the editor.

struct Wrapper: View {
    let selectedItem: PassthroughSubject<Item, Never>
    @State private var item: Item = Item.placeholder()
    
    var body: some View {
        EditorView(item: item)
            .onReceive(selectedItem) { newItem in
                item = newItem
            }
    }
}