iOS Development

ios – Is it okay to make use of shared ObservableObjects in SwiftUI views?


Shared ObservableObject is a handy technique to move information between views and it looks like it is working for monitoring and reacting to adjustments on revealed variables.

When it comes to SwiftUI design paradigm, is that this okay and a legitimate use of ObservableObject. Are there any downsides? If it’s not the proper approach, what could be the easiest way to trace adjustments for views which could have a protracted dad or mum hierarchy, at all times move down the thing from dad or mum?

Shared object instance:

class Obj: ObservableObject {
    
    static var shared = Obj()
    
    @Printed var modified = false
}

struct SwiftUIView: View {
    
    @ObservedObject var obj = Obj.shared
    
    var physique: some View {
        Button {
            obj.modified.toggle()
        } label: {
            Textual content("CHANGE")
        }
    }
}

struct OtherSwiftUIView: View {
    
    @ObservedObject var obj = Obj.shared
    @State var textual content = "HELLO"
    
    var physique: some View {
        Textual content(textual content)
            .onChange(of: obj.modified) { _ in
                textual content = "BYE"
            }
    }
}

What's your reaction?

Leave A Reply

Your email address will not be published.