chris
chris

Reputation: 15

ObservableObject bug or not

I still have the problem when the count reaches 3, the reset function only stops it, but the count is not set to 0. I use the reset function with a button, it works perfectly. i would like to understand it and hope someone knows the reason for it?

import SwiftUI
import Combine
import Foundation

class WaitingTimerClass: ObservableObject {

    @Published var waitingTimerCount: Int = 0

    var waitingTimer = Timer()

    func start() {
        self.waitingTimer = Timer.scheduledTimer(withTimeInterval: 1.0, repeats: true) { timer in
            self.waitingTimerCount += 1 }}

    func stop() { waitingTimer.invalidate() }

    func reset() { waitingTimerCount = 0; waitingTimer.invalidate() }

}

struct ContentView: View {

    @ObservedObject var observed = WaitingTimerClass()

    var body: some View {
        VStack {
        Text("\(self.observed.waitingTimerCount)")
            .onAppear { self.observed.start() }
                    .onReceive(observed.$waitingTimerCount) { count in
                        guard count == 3 else {return}
                        self.observed.reset()    // does not work
                    }

            Button(action: {self.observed.start()}) {
                Text("Start") }

            Button(action: {self.observed.reset()}) {     // works
                Text("Reset") }

            Button(action: {self.observed.stop()}) {
            Text("Stop") }
           }
        }
    }

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

Upvotes: 1

Views: 84

Answers (1)

Asperi
Asperi

Reputation: 258365

It is because reset changes property affecting UI during body construction, so ignored. It should be changed as below

func reset() {
    waitingTimer.invalidate()
    DispatchQueue.main.async {
        self.waitingTimerCount = 0
    }
}

Upvotes: 1

Related Questions