Sphere
Log in Join
☆ 7

SwiftUI view not updating when ObservableObject changes

SwiftUI, iOS 17, Xcode 16. I have a @StateObject viewModel in a parent, pass it to a child as @ObservedObject. The child shows a list from viewModel.items. When I append to items on a background thread after a network callback, the UI does not update. On the next unrelated state change it suddenly refreshes. Am I breaking the main-actor rule?

⚑ Report

4 replies

☆ 0
A async ·2026-10-21#1

Yes. ObservableObject.objectWillChange must fire on the main thread. If you mutate a @Published property off the main actor, the view may not get the update reliably. Dispatch it: DispatchQueue.main.async { self.items.append(newItem) }. Or mark the view model @MainActor so mutations are forced onto the main thread.

⚑ Report
☆ 0
G glitch ·2026-10-28#2

Dispatching the append to the main queue fixed it. I also marked the class @MainActor so the compiler catches future mistakes. The network callback was decoding on a background queue and writing straight to the published property. This is one of those things the compiler cannot help you with.

⚑ Report
☆ 0
P paper64 ·2026-10-29#3

With @MainActor you can just await the decode if you mark the parse method too, avoids the manual DispatchQueue dance. Also in iOS 17+ consider @Observable instead of ObservableObject, it is simpler and more granular about what triggers a redraw.

⚑ Report
☆ 0
G glitch ·2026-11-05#4

One gotcha with @Observable: it only tracks properties actually read by the view, which is great, but if you are coming from @Published on a class you need to adjust how you pass it around, no @ObservedObject needed. Worth it though.

⚑ Report
Log in to reply.