I just made a simple code of a timer, and am trying to figure out a way to NOT reset the timer when other observed object status is changed. When I start the timer with init function, it resets whenever other observed objects' status is changed. When I start the timer with onAppear, it gets changed once other observed objects' status is changed and never start again. What I want to accomplish is, the timer starts once and doesn't reset when other observed objects have changed during other observed objects are passed out from other View and the tiemr itself has to be Subview. Any suggestions?
import SwiftUI
import Combine
import Foundation
struct ContentView: View {
@ObservedObject var apptCardVM: ApptCardViewModel
@ObservedObject var timerData = TimerDataViewModel()
var body: some View {
VStack {
CurrentDateView(timerData: timerData) // << here !!
Picker("Seizure Type", selection: $apptCardVM.typeIndex) {
ForEach(0..<apptCardVM.typeChoice.count) {
Text(self.apptCardVM.typeChoice[$0])
}
}.pickerStyle(SegmentedPickerStyle())
}
}
}
struct CurrentDateView: View {
@State private var currentDate = Date()
let timer = Timer.publish(every: 1, on: .main, in: .common).autoconnect()
@ObservedObject var timerData: TimerDataViewModel
var body: some View {
Text("\(Int(timerData.hoursElapsed), specifier: "%02d"):\(Int(timerData.minutesElapsed), specifier: "%02d"):\(Int(timerData.secondsElapsed), specifier: "%02d")")
.fontWeight(.bold)
.textFieldStyle(RoundedBorderTextFieldStyle())
.onAppear(){
timerData.start()
}
}
}
class ApptCardViewModel: ObservableObject, Identifiable {
@Published var typeChoice = ["Quick", "Long", "FullService"]
@Published var typeIndex: Int = 0
private var cancellables = Set<AnyCancellable>()
}
class TimerDataViewModel: ObservableObject{
@Published var timer = Timer()
@Published var startTime : Double = 0.0
@Published var secondsOriginal = 0.0
@Published var secondsElapsed = 0.0
@Published var secondsElapsed_ = 0.0
@Published var minutesElapsed = 0.0
@Published var hoursElapsed = 0.0
enum stopWatchMode {
case running
case stopped
case paused
}
init(){
// start()
print("initialized")
}
func start(){
self.secondsOriginal = self.startTime
self.timer = Timer.scheduledTimer(withTimeInterval: 1, repeats: true){ timer in
self.secondsOriginal += 1
self.secondsElapsed_ = Double(Int(self.secondsOriginal))
self.secondsElapsed = Double(Int(self.secondsOriginal)%60)
self.minutesElapsed = Double(Int(self.secondsOriginal)/60 % 60)
self.hoursElapsed = Double(Int(self.secondsOriginal)/3600 % 24)
}
}
}