I’m developing a Swift class as a Manager that needs to fetch initial data from an API during initialization. I want to ensure that the class is fully initialized only after the data has been fetched and is available for use. Here’s a simplified version of what I’m trying to achieve:
import Foundation
class DataManager {
static let shared = DataManager()
private let apiService: APIService
private var data: [String] = []
private init(apiService: APIService = APIService()) {
self.apiService = apiService
// How can I ensure that the class waits for data fetching to complete before continuing initialization?
Task {
do {
self.data = try await self.fetchInitialData()
print("Initial data fetched: (self.data)")
} catch {
print("Error fetching initial data: (error)")
}
}
}
func fetchInitialData() async throws -> [String] {
// Example of fetching data asynchronously from API
let fetchedData = try await apiService.fetchData()
return fetchedData
}
var fetchedData: [String] {
return data
}
}
The reason I’m trying to do this is so that multiple ViewModels can rely on a single API call to fetch the data. However, I’m encountering a problem where sometimes I get an empty data list because the initialization hasn’t completed fetching the data before the data is accessed.