Home > Software design >  How can I use an observableobject class in an observableobject on SwiftUI?
How can I use an observableobject class in an observableobject on SwiftUI?

Time:01-11

I attached an image. Please see it.

1

As far as I know the "View" is only view. It's not controller. So Im developing like Way 1. But I faced a problem that how can I use observableobject in another observableobject?

I thought if I pass a parameter with the observableobject the problem will be clean. But I think it is bad way..

So I thought way 2. But the way is the "View" is not only view. It is view and controller.

So Im confused the way2 is bad way or not.

Which way is good way? and Im wondering other SwiftUI developers how to develop about this case.

Please advice me if you think there is better way than way1 & way2.

Summary

Q1. Way1 - How can I use observableobject in another observableobject? (singltone? like static shared)

Q2. Way2 - Is it correct way? (View = view controller)

Q3. Your advice.

Env

Xcode 14.2

Swift 5.7.2

CodePudding user response:

Here is the sample code for your question:

struct MainView: View {
     @StateObject var mainVM = MainViewModel()
     @ObservedObject var discoveryVM:DiscoveryViewModel

     var body: some View {
           ZStack {
                ScrollView {
                     // if data changed in DiscoveryViewModel view will automatically upadte
                     ForEach(discoveryVM.showProfiles, id: \.self) { profile in
                          MyView(profile: Profile)
                     }
                }
           }
           .onReceive(discoveryVM.$toggle) { status in 
           // change something in MainViewModel when toggle in DiscoveryViewModel
                mainVM.toggle = status // change variable(rearly used)
                mainVM.doSomething() // call fucntions
           }
     }
}


class MainViewModel: ObservableObject {
     @Published var toggle: Bool = false
     
     func doSomething() {
        print("Do something")
     }
}



class DiscoveryViewModel: ObservableObject {
     @Published var data: [ProfileModel] = []
     @Published var toggle: Bool = false
}

ObservableObjects are mostly used where there is nesting of views

  • Related