hmlongco / Factory

A new approach to Container-Based Dependency Injection for Swift and SwiftUI.
MIT License
1.93k stars 116 forks source link

Use InjectedObject in observable view model #246

Closed r0otx closed 1 month ago

r0otx commented 1 month ago

Thank you for library. I have problem. My app have repository, and mvvm architecture. All business logic make in view model, but if I add in vm InjectedObject(.profileRepository) var profileRepository show purple error: Accessing StateObject's object without being installed on a View. This will create a new instance each time. Why? How can fix it?

hmlongco commented 1 month ago

InjectedObject is meant for use injecting ObservableObjects into SwiftUI views. Use Injected in the VM.

r0otx commented 1 month ago

InjectedObject is meant for use injecting ObservableObjects into SwiftUI views. Use Injected in the VM.

If I use Injected in VM, UI can't reload after make changes. But if I use InjectedObject in view all right work :(

hmlongco commented 1 month ago

You can't use InjectedObject inside a view model and have it trigger updates any more that you can use another ObservableObject inside a view model and have it automatically trigger updates.

Use Injected to access the services your VM requires (e.g. APIs) and then assign the results to Published values in the VM.

r0otx commented 1 month ago

Is advice helped me https://stackoverflow.com/a/58406402