为什么来自 swift 包的视图似乎共享一个 ObservableObject 实例

Why do views from swift package seem to share an ObservableObject instance

我的 swift 包 UnsplashSwiftUI 有一个名为 UnsplashRandom 的视图,它使用 StateObject 从 UnsplashApi 异步获取数据。但是,如果您在同一页面上实现视图两次,即使它们应该不同,它们也会加载相同的图像。

我也尝试了一个 ObservedObject 如下,UnsplashApi 是我的 ObservableObject。

@StateObject var api = UnsplashApi() // Original
@ObservedObject var api = UnsplashApi() // This didn't work either

编辑:将 StateObject 标记为私有也不起作用

编辑:这是 UnsplashApi:

的实现
@MainActor
class UnsplashApi: ObservableObject {
    enum LoadingState {
        case idle
        case loading
        case loaded(UnsplashData)
        case failed(Error)
    }
    
    @Published var state: LoadingState = .idle
    
    func fetchImage(clientId: String, query: String, orientation: String) async {
        let baseUrl = URL(string: "https://api.unsplash.com/")
        guard var components = URLComponents(url: baseUrl!.appendingPathComponent("photos/random"), resolvingAgainstBaseURL: true)
        else { state = .failed(URLError(.badURL)); return }
        components.queryItems = [URLQueryItem(name: "client_id", value: clientId)]
        if query != "" {components.queryItems?.append(URLQueryItem(name: "query", value: query))}
        if orientation != "" {components.queryItems?.append(URLQueryItem(name: "orientation", value: orientation))}
        guard let url = components.url else { state = .failed(URLError(.badURL)); return }
        self.state = .loading
        do {
            let (data, _) = try await URLSession.shared.data(from: url)
            let response = try JSONDecoder().decode(UnsplashData.self, from: data)
            self.state = .loaded(response)
        } catch {
            state = .failed(error)
        }
    }
}

您的 fetchImage 方法使用 URLSession.shared。共享 URLSession 使用 URLCache。因此,您对 https://api.unsplash.com/photos/random 的第一个请求的响应很可能存储在缓存中,而后续请求 return 则存储在缓存的响应中。

尝试使用 URLSession(configuration: .ephemeral) 而不是 URLSession.shared