Correct approach to an Observable Factory #305
Answered
by
hmlongco
mikeymike9000
asked this question in
Q&A
-
|
For a view that reacts to a variable in a factory, is using a computed variable in the view model the best approach like so?: extension Container { var myRepo: Factory<MyRepo> { self { MyRepo() }.singleton }}
@Observable final class MyRepo {
var hash = 0
...
}
@Observable final class MyViewModel {
static let shared = MyViewModel()
@ObservationIgnored @Injected(\.myRepo) var myRepo
var hash: Int { myRepo.hash }
...
}
struct MyView: View {
@Bindable private var vm = MyViewModel.shared
var body: some View {
Text("hash", vm.hash)
}
}Also, is @InjectedObservable only for use directly in a view like so?: struct MyView: View {
@Bindable private var vm = MyViewModel.shared
@InjectedObservable(\.myRepo) var myRepo
var body: some View {
Text("hash", myRepo.hash)
}
}Thanks for any suggestions! Mike |
Beta Was this translation helpful? Give feedback.
Answered by
hmlongco
May 21, 2025
Replies: 1 comment 3 replies
-
|
Would probably roll this way... extension Container {
var myRepo: Factory<MyRepo> {
self { MyRepo() }.singleton
}
@MainActor
var myViewModel: Factory<MyViewModel> {
self { @MainActor in MyViewModel(container: self ) }
}
}
@Observable
final class MyRepo {
var hash = 0
func increment() {
hash += 1
}
}
@MainActor
@Observable
final class MyViewModel {
let myRepo: MyRepo
init(container: Container) {
self.myRepo = container.myRepo()
}
}
struct MyView: View {
@InjectedObservable(\.myViewModel) var vm: MyViewModel
var body: some View {
VStack {
Text("hash \(vm.myRepo.hash)")
Button("increment") {
vm.myRepo.increment()
}
}
}
}
#Preview {
MyView()
}Doing |
Beta Was this translation helpful? Give feedback.
3 replies
Answer selected by
mikeymike9000
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Would probably roll this way...