How to set static variable that requires async initialization ?
hypothetical case:
@globalActor public actor ImageDatabase{
public static var shared: ImageDatabase = ImageDatabase()
// 'async' call cannot occur in a global variable initializer
private var transport : ImageTransportLayer
private init() async {
self.transport = await ImageTransportLayer()
}
}
@ImageDatabase class ImageTransportLayer { } // CRUD
I doubt there is a way to create a global actor instance asynchronously. However, you can initialize your ImageTransportLayer later manually in the app launch sequence.
@globalActor public actor ImageDatabase {
private init() {}
public static var shared: ImageDatabase = ImageDatabase()
private var transport: ImageTransportLayer?
public func initTransport() async {
transport = await ImageTransportLayer()
}
}
@ImageDatabase class ImageTransportLayer {} // CRUD
Task {
await ImageDatabase.shared.initTransport()
// Continue using ImageDatabase.shared
}
That what I really would like to escape "to do it later" There's a chance that somebody might to forget to do it. I would like to escape to add extra State and check whether it's been initialized.