Hello everyone, I hope you are well. I have a question about .environment. I have an observable viewModel
which has some functions and publishing value. I'm observing this viewModel
in only 2 views but I'm using viewModel functions in every view. Should I use it (.environment)
. if I should use it, should I use this environment macro (@Environment(ViewModel.Self) var vm)
for only functions in view? Thank you so much.
Using .environment() for Observable Object
Hello :)
I would recommend you to use the .environment()
. Therefore you create one instance of your ViewModel in order to handle it through the hierarchy to be accessible whenever it is necessary. Apple shows us with this example:
@main
struct BookReaderApp: App {
@State private var library = Library()
var body: some Scene {
WindowGroup {
LibraryView()
.environment(library)
}
}
}
And for the LibraryView()
:
struct LibraryView: View {
@Environment(Library.self) private var library
var body: some View {
List(library.books) { book in
BookView(book: book)
}
}
}
You can find more information here. If you have any further questions don’t hesitate to ask.