I have a question about the logic of the @StateObject
. Let’s say we have a class initialised inside the view which has 0 @Published
properties, but we don’t want it to be reinitialised by the View
. Should it be made a @StateObject
to prevent that or is it bad practice to conform to ObservableObject
without having observable data. Example:
class Downloader {
private var isDownloading = false
func download(for id: String) {
isDownloading = true
// download
isDownloading = false
}
}
struct DummyView: View {
var downloader: Downloader()
var body: some View {
Text("Hello")
.onAppear {
downloader.download(for: "id")
}
}
}
2
Answers
your aim should be avoid class whenever you can, shared mutable state leads to bugs which is why SwiftUI uses
View
struct for view data,.task
makes it possible to do async work with no need for a class but still have the lifetime tied to something on screen, e.g.If the
Downloader
is only forSwiftUI.View
s you can put it into theEnvironment
.Then you can access it in any
SwiftUI.View
If you need to access the same instance of
Downloader
from non-Views you have to implement something similar toEnvironmentValues
.https://www.avanderlee.com/swift/dependency-injection/
I also suggest looking at the pros/cons of
actor
when dealing with something like a "Downloader" and actor can be beneficial.https://www.swiftbysundell.com/articles/swift-actors/