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.

Combine

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

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

Subscribers subscribe to one specific instance of the Publisher and receive data until the subscription is canceled. They conform to the Subscriber protocol.

Operators

Operators are needed to change data. For example, filter out nil, format data, etc.

Lets start

I'll show you an example using reactive code. Let's start with a model that we will fill from the API.

Network requests

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:

 

swiftui

 

More like this

Get in touch

Get in touch

Kharkiv, Ukraine

61023

Trinklera street, 9

+38 (050) 908-31-07

info@a5.ua

Frankfurt am Main, Germany

60354

Eckenheimer Schulstraße, 20

+38 (098) 630-49-85

info@a5.ua