Combine and SwiftUI
Swift was introduced at the WWDC 2014 Developers Conference. Apple recommends using the MVC architecture. As practice has shown, the usual MVC architecture is not enough for complex applications. At WWDC 2019, developers are shown SwiftUI and Combine, which should make an iOS developer's life better. Apple now recommends using the MVVM architecture. And now is the time to start understanding these technologies.
Main idea is Publishers send data to one or more subscribers, the data goes through Operators to Subscribers. Let's look in more details into terms used in this technology.
Publishers send values to one or more Subscribers. They conform to the Publisher protocol and declare the output type and any error they produce.
Subscribers subscribe to one specific instance of the Publisher and receive data until the subscription is canceled. They conform to the Subscriber protocol.
Operators are needed to change data. For example, filter out nil, format data, etc.
I'll show you an example using reactive code. Let's start with a model that we will fill from the API.
I will use URLSession for requests
Note the return type: AnyPublisher & lt; [TenantModel], Error & gt; is our publisher. We subscribe to it and receive data already in the ViewModel
.sink is a subscriber that receives data. self.tenants = tenants - Assign values to a variable marked with @Publisher. These changes will force the View to be updated
Add the @StateObject wrapper to catch all changes to the ViewModel. Here ForEach (Array (viewModel.tenants ...)) we go through the list, this list will rebuild itself when receiving data over the network.
Here's what we have to obtain: