Using .environment() for Observable Object

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.

Replies

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.

  • Thank you for you answer. So I have one last question left. I have view which is using only functions in view model. So not using the published value. Should I use it (@Environment(Viewmodel.self) var vm) or should I use var vm = viewModel() like that?

  • Of course! Even for this scenario I would recommend you to use @Environment(ViewModel.self) for flexibility and adjustment reasons (maybe another feature in a later version…). But I think you can use both without hesitation as long as it‘s working.

  • Thank you so much @Timo2303 :)

Add a Comment