UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

@EnvironmentObject problem

Forums > SwiftUI

I have problem with EnvironmentObject with triggering redrawn of multiple views at same time even the view is not active.


TabView(selection: $activeTab) {
  FavoriteContacts()
    .tag(Tab.Favorite)

   CallLogs()
     .tag(Tab.CallLogs)

    Contacts()
      .tag(Tab.Contacts)

    Dialer()
      .tag(Tab.Keypad)

    Conversations()
      .tag(Tab.Messages)
 }
 .environmentObject(contactModel)

In every view I have

@EnvironmentObject contactModel: ContactViewModel and in View I have debug property let _ = Self._printChanges() to know when redraw occures.

If I changed any property in my ContactViewModel _contactModel changed. is triggered within every single view in TabView. How can I force update only for current active view?

2      

This is not a problem of @EnvironmentObject but the essence of SwiftUI. Data drives UI, not the other way around. As you can read from here https://www.hackingwithswift.com/quick-start/swiftui/whats-the-difference-between-observedobject-state-and-environmentobject, you will notice this line. -> Think of @EnvironmentObject as a massive convenience for times when you need to pass lots of data around your app. Because all views point to the same model, if one view changes the model all views immediately update – there’s no risk of getting different parts of your app out of sync.

2      

So there is no way to update only view which is currently active? This essence of SwiftUI making me a trouble. Im using 3rd party library and that library seems making API call on evevery update of the view.

Example from the app, API returning presence of the contacts, but I have multiple views linked to the same model, and if presence is updated I got updated multiple views at the same time which are not even visible and API is called for each view instead of once.

So in the logs I see same contact for multiple times.

2      

Not sure of logic in your model, however if the property marked as @Published in your model it will notify all the views using this property to update themselves. If property is not a publisher then in this case it will not ask the views using it to refresh.

2      

BUILD THE ULTIMATE PORTFOLIO APP Most Swift tutorials help you solve one specific problem, but in my Ultimate Portfolio App series I show you how to get all the best practices into a single app: architecture, testing, performance, accessibility, localization, project organization, and so much more, all while building a SwiftUI app that works on iOS, macOS and watchOS.

Get it on Hacking with Swift+

Sponsor Hacking with Swift and reach the world's largest Swift community!

Reply to this topic…

You need to create an account or log in to reply.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.