0

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
}
3
  • I highly recommend to use a Timer Publisher from the Combine framework Commented Jul 31, 2022 at 7:32
  • @Published needs to be a value type, e.g. a struct or an array or structs. Commented Jul 31, 2022 at 11:00
  • ObservedObject Wrapper can’t be inside a class it has to be in a View. Also the object will change line is redundant. Commented Jul 31, 2022 at 11:14

1 Answer 1

0

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.