Update:
Apparently it's better to pass the initializer of the model directly to the StateObject(wrappedValue:). (Watch this Youtube Video and follow the description for more.)
The sample code can be changed to:
@StateObject private var amplifyConfig: AmplifyConfig
init() {
self._amplifyConfig = StateObject(wrappedValue: AmplifyConfig())
if !_amplifyConfig.wrappedValue.isAmplifyConfigured {
_amplifyConfig.wrappedValue.dataStoreHubEventSubscriber()
_amplifyConfig.wrappedValue.configureAmplify()
}
}
From iOS 15.0 onwards, there is a new modifier available named .task(priority:_:). You can use it to also run some of your initialization code for amplifyConfig.
@StateObject private var amplifyConfig: AmplifyConfig = .init()
init() {}
var body: some View {
VStack {
// Your content
}
.task { // This can be attached to all `View` types, not only a `VStack`.
if !amplifyConfig.isAmplifyConfigured {
amplifyConfig.dataStoreHubEventSubscriber()
amplifyConfig.configureAmplify()
}
}
}
Original Answer
I came across this thread, accepted answer doesn't work for my use case although it is correct. I fixed it using the following solution.
You could also initialize the AmplifyConfig in the init yourself, then assign it to @StateObject var .... Like below:
@StateObject private var amplifyConfig: AmplifyConfig
init() {
let amplifyConfig = AmplifyConfig()
self._amplifyConfig = StateObject(wrappedValue: amplifyConfig)
if !amplifyConfig.isAmplifyConfigured {
amplifyConfig.dataStoreHubEventSubscriber()
amplifyConfig.configureAmplify()
}
}