Accessing StateObject’s object without being installed on a View. This will create a new instance each time – SwiftUI

You cannot access any value before they get initialized, use onAppear():

import SwiftUI

@main
struct YourApp: App {
    
    @StateObject private var amplifyConfig: AmplifyConfig = AmplifyConfig()
    
    var body: some Scene {
        
        WindowGroup {
            ContentView()
                .onAppear() {
                    if (!amplifyConfig.isAmplifyConfigured) {
                        amplifyConfig.dataStoreHubEventSubscriber()
                        amplifyConfig.configureAmplify()
                    }
                }
        }
    }
}

Update: An actual use case

import SwiftUI

@main
struct YourApp: App {
    
    @StateObject private var amplifyConfig: AmplifyConfig = AmplifyConfig()
    
    @State private var isLoaded: Bool = Bool()
    
    var body: some Scene {
        
        WindowGroup {
            
            VStack {
                if (isLoaded) { ContentView() }
                else { Text("Loading . . .") }
            }
            .onAppear() {
                if (!amplifyConfig.isAmplifyConfigured) {
                    amplifyConfig.dataStoreHubEventSubscriber()
                    amplifyConfig.configureAmplify()
                    completionHandler { value in isLoaded = value }   
                }
                else {
                    isLoaded = true  
                }
            }
        }   
    }
}


func completionHandler(value: @escaping (Bool) -> Void) {
    
    // Some heavy work here, I am using DispatchQueue.main.asyncAfter for replicating that heavy work is happening! But you use your own code here.
    DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + DispatchTimeInterval.milliseconds(3000)) { value(true) }

}

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)