Airlist
Contact, Follow, Help & Guide
Building with SwiftUI: Managing State
2022-01-29

We built Airlist for the web with Vue, which out of the box comes with its own global state management library.

So naturally, when building Airlist with SwiftUI, it made sense to follow the same paradigm (i.e. Redux). A global state variable that was passed around by an environmentObject.

At first, it went fantastic. Easy to maintain, simple to implement, and very fast… until it wasn’t.

Suddenly, as more Airlist features were built out, and as datasets got larger, the app became slow. Very slow.

Simple interactions stuttered. Animations were anything but smooth.

After running some tests (commenting out code) it became clear. If a view accessed the global state variable through .environmentObject, that view was updated when the global state was updated. Or at least check if it should be updated.

Since SwiftUI is still in its infancy, there isn’t a clear understanding on what you /should do. /

Implementing Services Model

Instead of using a single global variable, I embraced @ObservableObject.

I broke the app down into mini “services”. Is the menu up or down? MenuService. Is CommandCenter open? CommandCenterService. Which item is being viewed? FocusService. Mark and item complete? ItemService.

A service looks like this:

class MenuService: ObservableObject {
    @Published var isOpen: Bool = false

    // this is important, ensures there is only 1 instance
    static let shared = MenuService()
    private init() {
        // do any setup here
    }

    func doSomething() {
        // do something here
    }
}

If a view needs to know if the menu is open, I simply add:

@ObsesrvedObject var menuService = MenuService.shared

Then I can do something like

if menuService.isOpen {
  // do something
}

The Results

Since implementing my services model, every interaction is buttery smooth. All the slow downs I was seeing are gone. On top of this, I find this model easier to maintain, add, and update than using a Global State variable.


Airlist for iPhone just about ready for a public beta. To be the first to know sign up for our newsletter below:

We hate spam too. You’ll only receive periodic important Airlist information. Unsubscribe anytime.

We’re also posting more regular and in-depth updates on our twitter.

Join the Public Beta
Keep your data. Easy import & export.
No commitment required.