Post

Replies

Boosts

Views

Activity

Observable / State memory leak on view updates
I am working on a app that uses the new Observation framework and MVVM design pattern. I have a view composed of a list and a header that shows statistics about the displayed content by using an Observable ViewModel. When I add new contents, it is added to the list but the header seems to not take it into account even if its init method and body property are called. @Observable final class ViewModel { let contents: [String] init(contents: [String]) { self.contents = contents print("ViewModel init") } deinit { print("ViewModel deinit") } } struct ContentHeaderView: View { @State private var viewModel: ViewModel init(contents: [String]) { self._viewModel = State( initialValue: ViewModel(contents: contents) ) } var body: some View { Text("\(self.viewModel.contents.count)") } } struct ContentListView: View { @State private var contents = ["Content 1"] var body: some View { NavigationStack { VStack { ContentHeaderView(contents: self.contents) List(self.contents, id: \.self) { content in Text(content) } } .toolbar { ToolbarItem { Button("Add Content") { let newContent = "New Content \(self.contents.count + 1)" self.contents.append(newContent) } } } } } } In this example, when I tap the "Add Content" toolbar button, the header view that's supposed to show the number of content still display "1" even if the array now contains 2 elements. I added print statements to show that a new ViewModel is created every time the view is updated and the currently displayed view still uses the first created ViewModel which in fact contains a array with only one element. ContentHeaderView Init // on appear ContentHeaderView Init // First button tap // Every other tap ContentHeaderView Init ContentHeaderView Deinit I've read the threads 736239 and 736110 that discusses about similar issues when presenting sheets. I have similar code without issues since it's been fixed in iOS 17.2 beta 1 but it seems to still happen on view updates. Can you please confirm that this is an issue with the Observable framework and State properties or is there something I'm doing wrong ? Thanks
0
0
640
Dec ’23