Skip to main content
Post Closed as "Duplicate" by Rob swift
Non-related tags
Link
Steven-Carrot
  • 3.2k
  • 3
  • 20
  • 50
edited tags
Link
Source Link

ObservableObject doesn't update view with TImer

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
}