简体   繁体   中英

How "expensive" is @Published (SwiftUI)

I am using ObservableObject and @Published protocol and property wrapper, respectively, to asynchronously update my view structs with fetched data (in this case images). This is working fine, though I'm wondering if there might be a less "expensive" way. The image I'm fetching (profile picture) is essentially static except for the asynchronous fetching process. I'm not sure how expensive (for memory or runtime) @Published is, but I sense that there might be a more efficient solution. Is there?

Code:

class ImageFetcher: ObservableObject {
    var firebaseManager: FirebaseManager
    @Published var image: UIImage? = nil

    init(_ firebaseManager: FirebaseManager) {
        self.firebaseManager = firebaseManager
    }

    func fetchImage(id: String) {
        let ref = getRefURL(uid: id)
        print(ref)
        ref.getData(maxSize: 2051240) { data, error in
            if let error = error {
                print("Error: \(error)")
                return
            }
            self.image = UIImage(data: data!)
        
        }
    }

    func getRefURL(uid: String) -> StorageReference {
        return firebaseManager.STORAGE.reference().child(uid)
    }
}


struct ImageView: View {
    @ObservedObject var fetcher: ImageFetcher

    init(_ firebaseManager: FirebaseManager) {
        self.fetcher = ImageFetcher(firebaseManager)
    }


    var body: some View {

        Button {
            fetcher.fetchImage(id: "QDhKhNe5VnWDCORoQScIVVzcpzv2")
        } label: {
            Text("Load Image")
        }

        if fetcher.image == nil {
            Text("Loading...")
        } else {
            Image(uiImage: fetcher.image!)
                .resizable()
                .frame(width: 50, height: 50)
        }
    }
}

Note: The code includes objects defined elsewhere in my code as well as references to my storage (which you won't be able to access) so the code is intended to be read, but not necessarily run, as it won't work.

So the performance of @Published isn't that bad. SwiftUI is built to be able to handle multiple reloads of the view (which happens when an value is set to a @Published). So if you want to keep this architecture i would suggest removing the @Published and then use objectWillChange.send() to control when your view will update. @Published is kind of made for combine, and it doesn't seem like you are using it.

Personally i don't use classes / ObservableObject at all.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM