CodexBloom - Programming Q&A Platform

Strange behavior when using SwiftUI's onReceive with Combine in iOS 17

👀 Views: 85 💬 Answers: 1 📅 Created: 2025-06-13
swift swiftui combine Swift

I'm not sure how to approach I'm updating my dependencies and I'm trying to configure I'm working on a personal project and I'm stuck trying to I've been banging my head against this for hours..... I am encountering an issue with my SwiftUI app where I am trying to update my view based on changes in a Combine publisher. I have a `@State` variable that should be updated every time the publisher emits a new value. However, it seems that the `onReceive` modifier is not triggering consistently. Here’s a simplified version of what I’ve implemented: ```swift import SwiftUI import Combine class TimerPublisher: ObservableObject { @Published var time: Int = 0 private var cancellable: AnyCancellable? init() { cancellable = Timer.publish(every: 1, on: .main, in: .common) .autoconnect() .sink { [weak self] _ in self?.time += 1 } } } struct ContentView: View { @StateObject private var timer = TimerPublisher() @State private var displayTime: String = "" var body: some View { Text(displayTime) .onReceive(timer.$time) { newTime in displayTime = "Time: \(newTime)" } } } ``` In this setup, I expect the `displayTime` to update every second. However, sometimes it doesn’t reflect the latest time until I perform an action like tapping on the screen. I’ve tried wrapping `displayTime` in `DispatchQueue.main.async`, but that didn’t help. I also checked that my Combine publisher is working correctly and confirmed that the `print` statement within the sink is executing every second. This inconsistency makes me think there might be an issue with the SwiftUI view updating mechanism. Is there something I’m missing here regarding how `onReceive` works with `@StateObject`? Or could this be an issue related to iOS 17's SwiftUI updates? Any suggestions on how to ensure the UI updates reliably would be greatly appreciated! This is part of a larger CLI tool I'm building. What's the best practice here? I'm developing on Windows 11 with Swift. Thanks, I really appreciate it! I recently upgraded to Swift latest. Any pointers in the right direction? Any examples would be super helpful. I'm on Windows 10 using the latest version of Swift. I appreciate any insights!