When using conformance to ObservableObject
and then doing async work in a Task,
you will get a warning courtesy of Combine
if you then update an @Published
or @State
var from anywhere but the main thread. However, if you are using @Observable
there is no such warning.
Also, Thread.current
is unavailable in asynchronous contexts, so says the warning. And I have read that in a sense you simply aren't concerned with what thread an async task is on.
So for me, that begs a question. Is the lack of a warning, which when using Combine is rather important as ignoring it could lead to crashes, a pretty major bug that Apple seemingly should have addressed long ago? Or is it just not an issue to update state from another thread, because Xcode is doing that work for us behind the scenes too, just as it manages what thread the async task is running on when we don't specify?
I see a lot of posts about this from around the initial release of Async/Await talking about using await MainActor.run {}
at the point the state variable is updated, usually also complaining about the lack of a warning. But ow years later there is still no warning and I have to wonder if this is actually a non issue. On some ways similar to the fact that many of the early posts I have seen related to @Observable
have examples of an @Observable
ViewModel instantiated in the view as an @State
variable, but in fact this is not needed as that is addressed behind the scenes for all properties of an @Observable
type.
At least, that is my understanding now, but I am learning Swift coming from a PowerShell background so I question my understanding a lot.