#Swift #SwiftUI #Concurrency #StateObject #NotificationCenter

Just ran into a question on how to implement NotificationCenter long-running listeners with modern AsyncSequence API, and have them torn down correctly. This seems to work.

https://forums.swift.org/t/deinit-not-called-in-certain-scenarios-with-for-await-loop/64198/19

Deinit not called in certain scenarios with for await loop

I just ran into this, and wanted to share a recipe that works for me. I have a SwiftUI View with the associated ViewModel that’s owned by the view as a StateObject. I want the viewModel to be able to react to a bunch of notifications with the modern async API and long-running AsyncSequences, and for everything to be deallocated correctly when the view ends. I don’t want to code anything by hand and want things to happen automatically with the highest-level code possible. Here’s what I came up w...

Swift Forums

#SwiftUI #StateObject

Yesterday we got some important info about how to initialize a StateObject with external values. https://mastodon.social/@lucabernardi/109948882720031817

Here’s a small exercise I did around that. All the behavior makes sense. You see all the ViewModels are only initialized once.

It’s not clear to me why the documentation uses a closure in example code for “Initialize state objects using external data”. StateObject initializer wrappedValue is already an autoclosure.