Swift Nested ObservableObject not updating Timer view

I’m trying to program a small interval timer application with Swift and am stuck on not being able to update my view probably.
The view is updated only when one interval ends, so the timer gets to 0 and a new interval starts with a new time.

I thought that I wouldn’t have to do much because of the ObservableObjects and the @Published declaration, but it seems I have some crucial error in my logic about swift and interaction between views and models?

I have an TimerClockView for the timer embedded in my RunningTimerView. An IntervalTimerViewModel for logic stuff and connection, though I don’t think it’s properly done and has space for improvement. Then my MyTimer class for the timer stuff.

For readability I shorten my classes..

TimerClockView

struct TimerClockView: View {
    @ObservedObject var viewModel: IntervalTimerViewModel
// some code
    
    var body: some View {
        ZStack {
// some code
            if viewModel.isPlaying {
                Text("(viewModel.myTimer.currentProcessingDurationString)")
                    .font(.system(size:  customSize * 0.25))
                Text("(viewModel.myTimer.getTotalInMinutes())")
                    .offset(y: customSize * 0.2)
                    .font(.system(size:  customSize * 0.15))
            } else {
                Text("(viewModel.myTimer.getTotalInMinutes())")
                    .font(.system(size: customSize * 0.25))
            }
        }
        .foregroundStyle(currentColor)
    }
}

RunningTimerView


struct RunningTimerView: View {
    @ObservedObject var viewModel: IntervalTimerViewModel
    // some code
    
    var body: some View {
        ZStack {
            VStack {
                // some code
                TimerClockView(viewModel: viewModel,customSize: UIScreen.main.bounds.width * 0.8)
// some code
            }
            .background(currentColor)
        }
    }
}

IntervalTimerViewModel


class IntervalTimerViewModel: ObservableObject {
    @Published var settings: Settings
    @Published var intervalProfile: IntervalProfile
    @Published var myTimer: MyTimer
    @Published var currentInterval: Interval?
    @Published var currentExercise: Exercise?
    @Published var volumeLevel: Float = 50
    @Published var intervalMode: IntervalMode?
    @Published var currentActivityType: ActivityType = .none
    @Published var isPlaying: Bool = false
    var currentRound: Int = 1
    var totalRounds: Int = 0
    var totalExercises: Int = 0
    var currentExerciseIndex: Int = 0
    
    init(intervalProfile: IntervalProfile, settings: Settings) {
        self.settings = settings
        self.intervalProfile = intervalProfile
        self.myTimer = MyTimer()
        
        guard let interval = intervalProfile.intervals.first else { return }
        
        self.currentInterval = interval
        self.currentExercise = interval.exercises.first
        self.totalRounds = interval.roundCounter
        self.totalExercises = interval.exerciseCounter
        self.intervalMode = interval.intervalMode
        setCurrentTimer(interval: interval)
        setTimerListener()
    }
    
    func skipToNextExercise() -> Bool {
        // some code
    }
    
    func setCurrentTimer(interval: Interval?) {
        if let interval = interval {
            myTimer.setTimes(exercises: interval.exerciseCounter, repetition: interval.roundCounter,  activityDuration: interval.activityDuration, pauseDuration : interval.pauseDuration, variableDuration: interval.variableDuration, currentProcessingDuration: interval.activityDuration, warmUpTime: settings.defaultWarmUpTime)
        }
    }
    
    func setTimerListener() {
        myTimer.onExercisePauseTimerEnd = { [weak self] in
            self?.setNextActivity()}
    }
    
// for when one interval ends and the next starts
    func setNextActivity() {
        guard let interval = currentInterval else { return}
        print("(currentActivityType)")
        switch currentActivityType {
        case .none:
            myTimer.currentProcessingDuration = settings.defaultWarmUpTime
            currentActivityType = .warmUp
            break
        case .activity:
            if currentExerciseIndex + 1 < interval.exercises.count {
                currentExerciseIndex += 1
                currentExercise = interval.exercises[currentExerciseIndex]
                myTimer.currentProcessingDuration = interval.pauseDuration
                currentActivityType = .pause
            } else {
                if currentRound < totalRounds {
                    currentRound += 1
                    currentExerciseIndex = 0
                    currentActivityType = .roundPause
                    myTimer.currentProcessingDuration = interval.variableDuration
                } else {
                    stopTimer()
                    return
                }
            }
            break
        case .pause:
            currentExercise = interval.exercises[currentExerciseIndex]
            myTimer.currentProcessingDuration = interval.activityDuration
            currentActivityType = .activity
            break
        case .roundPause:
            currentExerciseIndex = 0
            currentExercise = interval.exercises[currentExerciseIndex]
            myTimer.currentProcessingDuration = interval.activityDuration
            currentActivityType = .activity
            break
        case .warmUp:
            currentExerciseIndex = 0
            currentExercise = interval.exercises[currentExerciseIndex]
            myTimer.currentProcessingDuration = interval.activityDuration
            currentActivityType = .activity
            break
        case .coolDown:
            print("")
            // not yet implemented
            // Method could be used to define cooldown after sesion for stretching or whatever
            break
        }
        startTimer()
        
    }
    
    func startTimer() {
        if !isPlaying {
            changeVolume()
            myTimer.startTimer()
            isPlaying = true
        }
    }
    
    func pauseTimer() {
        if isPlaying {
            changeVolume()
            myTimer.pauseTimer()
            isPlaying = false
        }
    }
    
    func continueTimer() {
        if !isPlaying {
            changeVolume()
            isPlaying = true
            myTimer.continueTimer()
        }
    }
    
    func stopTimer() {
        isPlaying = false
        changeVolume()
        myTimer.stopTimer()
        resetActivities()
    }
// some code
}

MyTimer


class MyTimer: ObservableObject {
    @Published var totalDuration: Int = 0
    @Published var currentProcessingDuration: Int = 0
    @Published var totalDurationString: String = ""
    @Published var currentProcessingDurationString: String = ""
    @Published var audioPlayer: AVAudioPlayer?
    private var lastCurrentProcessingDuration: Int = 0
    var onExercisePauseTimerEnd: (() -> Void)?
    @Published var timer: Timer?
    
    init() {
        audioPlayer = AVAudioPlayer()
        audioPlayer?.volume = loadAudioVolume()
    }
    
    func setTimes(exercises: Int = 0, repetition: Int = 0, activityDuration: Int = 0, pauseDuration : Int = 0, variableDuration: Int = 0, currentProcessingDuration: Int = 0, warmUpTime: Int = 0) {
        let totalActivity = exercises * activityDuration * repetition
        let activityPause = exercises * pauseDuration * repetition
        let roundPause = (repetition - 1) * variableDuration
        self.totalDuration = totalActivity + activityPause + roundPause + warmUpTime
        self.currentProcessingDuration = currentProcessingDuration
        self.totalDurationString = getTotalInMinutes()
        self.currentProcessingDurationString = getCurrentProcessingInMinutes()
    }
    
    
    
    func startTimer() {
        configureAudioPlayer(audioName: "startIntervalSound")
        timer?.invalidate()
        timer = Timer.scheduledTimer(withTimeInterval: 1.0, repeats: true) {
            [weak self] _ in  DispatchQueue.main.async {
                self?.tick()
            }
        }
    }
    
    func tick() {
        print("currentProcessingDuration: (currentProcessingDuration)")
        print("totalDuration: (totalDuration)")
        if currentProcessingDuration == lastCurrentProcessingDuration {
            configureAudioPlayer(audioName: "beepStartSound")
        }else if currentProcessingDuration <= 4 && currentProcessingDuration > 0 {
            configureAudioPlayer(audioName: "beepSound")
        }
        if currentProcessingDuration == 0 {
            configureAudioPlayer(audioName: "beepEndSound")
            onExercisePauseTimerEnd?()
        }
        if currentProcessingDuration > 0 && totalDuration > 0 {
            currentProcessingDuration -= 1
            totalDuration -= 1
            self.totalDurationString = getTotalInMinutes()
            self.currentProcessingDurationString = getCurrentProcessingInMinutes()
        }
        if(totalDuration == 0) {
            stopTimer()
            return
        }
    }
    
    func pauseTimer() {
        configureAudioPlayer(audioName: "pauseIntervalSound")
        timer?.invalidate()
    }
    
    func continueTimer() {
        configureAudioPlayer(audioName: "continueIntervalSound")
        lastCurrentProcessingDuration = currentProcessingDuration
        startTimer()
    }
    func stopTimer() {
        configureAudioPlayer(audioName: "stopIntervalSound")
        timer?.invalidate()
        timer = nil
        AudioServicesPlaySystemSound(1100)
    }
    
    func getTotalInMinutes() -> String {
        return  getTimeInMinutes(processedTime: totalDuration)
    }
    func getCurrentProcessingInMinutes() -> String {
        return  getTimeInMinutes(processedTime: currentProcessingDuration)
    }
    func getTimeInMinutes(processedTime: Int) -> String {
        return String(format: "%d:%02d", processedTime / 60, processedTime%60)
    }
// some code    
}

Till now I tried to use different timers, timer.scheduledTimer and timer.publish to see if that makes any difference. I tried to save the new value in different variables throughout my view model and myTimer and tried to use a listener callback when counting the time, like I have for when one interval finishes (currentProcessingDuration = 0). I tried to introduce the timer at different space because I thought maybe I call another object but it doesn’t seems like it.
ChatGPT-4 says my code is fine and the ObservableObject/ObservedObject/@Published should work like its intended…

Could someone give me some hints for solving my problem? Thank you!

New contributor

Innoriam is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật