ObservableObject bug or not

为君一笑 提交于 2020-03-03 07:47:48

问题


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()
    }
}


回答1:


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
    }
}


来源:https://stackoverflow.com/questions/60476678/observableobject-bug-or-not

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!