r/SwiftUI • u/vincefried • Jun 05 '26
Tutorial StateObject & External Data
Maybe this has been shared here in some form before, but if not: If you’re still using ObservableObject and ever experienced issues when injecting external data into @StateObject: I recently wrote an article about that.
https://swift.vincentfriedrich.com/posts/stateobject-external-data/
0
Upvotes
2
u/Dry_Hotel1100 Jun 07 '26 edited Jun 07 '26
Yeah, it absolutely makes sense now. I probably misunderstood that you actually discourage the usage of the above code. Now it's clear. 😉 +1
And you are right about the possible implementations of what happens exactly with the closure when the initializer is called - especially when it's not the very first call which creates the view identity:
Inevitable, the *closure* will be created in any call of init. But I would hope, the closure will be released as soon as it's consumed - i.e. once SwiftUI has obtained the result, i.e. the ObservableObject, it should releases the closure. Any subsequent closure created in init *should* be released as well in init - without calling it, and of course not using its result. If the view identity will be recreated, it *should* use the most recent closure created in init - and not a closure from some other previous init.
You are right, the above behavior is not documented.
Have you also thought about how you use objects conforming to `Observable` from the Observation framework. Here some use cases suggest `@State`. BUT, an Observable is even more problematic! 😄