Use Combine to update UI

Tram Ho

What is a Combine framework? According to what I read, this new framework is similar to RxSwift. Combine allows us to declare reactive functions by using pre-defined Swift APIs. For example, we declare a property named X, when the value of X changes, our interface will also be automatically updated. As in Rxswift, we are all familiar with two concepts: Obserables and Observers. In the Combine framework, there are two similar guys: Publishers <=> Observables Subcribers <=> Observers

Let’s find out through the example:

In this article, I will use the SwiftUI and Combine framework to implement an example as follows: Request api, and display it on the List First, I need to prepare a url, after searching the internet, I can search Get 1 API as follows:

In this example I will use alamofire to request api. After the network has been built, I will proceed to build my UI UI simply 1 List to display the following data: Here is the code I build the UI, this is in the ContentView.swift file:

Here, I use Codable to bind data, so I prepare 2 objects as follows:

  • Identifiable is a protocol built in to help List be able to distinguish between separate rows. When the object conforms to this protocol, we must declare an attribute named id. And the data type of this id attribute must be Hashable (Int, Double, String)

Building ObserverObject.

ObservableObject is a new protocol provided. According to the apple documentation, an ObservableObject will emit the value changed before any @Published properties are changed. Published is a generic structure used to initialize a publisher property. Next, I will create a class to handle the response from the api request and data processing:

-> In the above class, make sure it conforms to the ObservableObject protocol. Inside, I created 2 properties: jokes and isShow. Both of these properties are known as Publisher via the keyword @Published . Understand that, when the api request data is successful, the data is assigned to these two properties, the UI will be updated.

Next, I will return to the UI screen I just created, in the ContentView.swift file, this time the full will be:

-> According to the interface above, the List will subcribe the Publisher data as the jokes I just created in the JokesObserver class. After the api request is successful, this time the data will automatically be updated to the UI. Thank you for reading through this article Link example github: https://github.com/dungkv-1044/Learning1/tree/master/Learning1

Share the news now

Source : Viblo