How to initialize @Observable object in View via @State?

When I switched to observable, I noticed a strange behavior of the ViewModel. The ViewModel is created 3x times. And my question is: How to properly initialize the ViewModel via state?

Below is a minimal example with log output:

ViewModel INIT  : EBBB2C41
ViewModel INIT  : D8E490DA
ViewModel INIT  : 54407300
ViewModel DEINIT: D8E490DA
@Observable
final class ViewModel {
    
    @ObservationIgnored let idd: UUID

    init() {
        idd = UUID()
        print("ViewModel INIT  : \(idd.uuidString.prefix(8))")
    }
    
    deinit {
        print("ViewModel DEINIT: \(idd.uuidString.prefix(8))")
    }
}

struct SimpleView: View {
    @Environment(ViewModel.self) private var viewModel

    var body: some View {
        @Bindable var viewModel = viewModel
        Text("SimpleView: \(viewModel.idd.uuidString.prefix(8))")
    }
}

struct ContentView: View {

    @State private var viewModel = ViewModel()

    var body: some View {
        SimpleView()
            .environment(mainViewModel)
    }
}

@nikita_cz That seem's odd and based off your code snippet ViewModel should only be instantiated once.

First, could open a bug report, include the code snippet you provided, and the test environment. Post the FB number here once you do.

Bug Reporting: How and Why? has tips on creating your bug report.

How to initialize @Observable object in View via @State?
 
 
Q