Getting Started

To set up a SwiftUI list that displays the data from a web API, we need to set up an ObservableObject class as shown below:

The map operator transforms the API result into a new publisher which returns the data from the API response.

It’s important to set receive(on:) to the main thread to update the list and to store the subscription in a cancellable instance, in order to keep it alive.

We’ll use this data at the next step to decode the JSON by using the Codable protocol as shown below:

The HNItem struct needs to conform to the Identifiable protocol for the SwiftUI list to distinguish each row from the others.

The results from the API are set on the hnItems property of the HackerNewsFeed class. Since it has a Published property wrapper, the changes are reflected in the SwiftUI list as shown below:

Subsequently, we get the following result in our simulator:

SwiftUI list without endless scroll