Home > other >  ObservableObject doesn't update view with TImer
ObservableObject doesn't update view with TImer

Time:07-31

I'm trying to understand why StateObject doesn't update my Text view while it's being updated by timer inside ObservableObject. I would really appreciate any explanation.

struct DailyNotificaitonView: View {
    @StateObject var x = Test2()
    
    var body: some View {
        VStack {
            Text("\(x.progress.x)")
                .onAppear {
                    Timer.scheduledTimer(withTimeInterval: 1, repeats: true) { _ in
                        DispatchQueue.main.async {
                            print(x.progress.x)
                        }
                    } 
              }
        }
    }

ObservableObject:

class Test2: ObservableObject {
    @ObservedObject var progress = Test()
    
    init() {
        Timer.scheduledTimer(withTimeInterval: 1, repeats: true) { _ in
            DispatchQueue.main.async {
                self.update()
            }
        }
        
        
    }
    
    func update() {
        print("updated")
        progress.x  = 1
        progress.y  = 1
    }
}

class Test: ObservableObject {
    @Published var x: Int = 0 {
        willSet {
            objectWillChange.send()
        }
    }
    @Published var y: Int = 0
}

CodePudding user response:

At a high level, the issue you are having is that progress is not an @Published value, e.g. struct or array, which is necessary for an ObservedObject to receive the state changes. At its core, the published/observed system in SwiftUI is designed to have an observed object directly reference a published value.

CodePudding user response:

unfortunately nested observable objects do not work in swiftui however there is a workaround in this thread

How to tell SwiftUI views to bind to nested ObservableObjects

  • Related