Binding the User Interface and Data Using Combine

Combine was introduced by Apple at WWDC 2019. Apple states in the documentation that Combine provides a declarative Swift API for processing values over time. This is exactly what we (and most apps in general) need. We have data that has accumulated as a result of system events, and we want to process this data such that it can be shown in the user interface.

Combine declares publishers that emit data and subscribers that receive data. In our case, the location provider will publish the day entries and the user interface will subscribe to that data. Let’s start with the publisher.

Open LocationProvider and replace the property declaration of dayEntries with the following line of code:

 @Published​ ​var​ dayEntries: [​DayEntry​] = []

By adding the attribute @Published to the property declaration of regionUpdates, we create a publisher that emits values when the array changes. Next, replace the declaration of LocationProvider with the following line of code:

 class​ ​LocationProvider​: ​NSObject​,
 CLLocationManagerDelegate​,
 ObservableObject​ {

With this change, we make LocationProvider an observable object that emits the changed values before the @Published properties change.

To subscribe to the changes, we transform the locationProvider property into an environment variable. Replace the declaration of locationProvider in ContentView with the following line of code:

 @EnvironmentObject​ ​private​ ​var​ locationProvider: ​LocationProvider

Using @EnvironmentObject, we can pass into the class ContentView an object that can be bound to. Whenever the environment object changes, the view gets invalidated, which triggers the update of the view. Note that we removed the assignment in this line of code because this is managed by Combine.

The user interface is now bound to the day entries array. Next we’ll build the SwiftUI view of a single day entry.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.223.125.219