Combine introduction

Combine framework is a new framework released in iOS13. It is a declarative syntax for processing various event flows, which is easy to maintain and readable. Similar to the current popular RxSwift and RA responsive programming, apple finally implemented the Combine framework by itself.

  • Publisher acts as an event source that generates events
  • Subscriber as the receiver of the event

Explore the application of Combine in UITextField

Listen for changes to UITextField text.

viewDidLoad() {
    textTF.publisher(for: \.text).sink { (text) in
            print(text)
    }
}
    
Copy the code

Cancellable (cancellable) : cancellable (cancellable) : cancellable (cancellable) : cancellable (cancellable) : cancellable (cancellable) : cancellable (cancellable) : cancellable (cancellable) : cancellable (cancellable)

var cancellable: AnyCancellable?
override viewDidLoad() {
    super.viewDidLoad()
    cancellable = textTF.publisher(for: \.text).sink { (text) in
            print(text)
    }
}
Copy the code

The text attribute of UITextField complies with KVO. Normally, when the keyboard input text changes, it will trigger the printing log, so it is supposed that the keyboard input did not trigger the change method caused by KVO. We added target-Action to TextField. After searching for Publisher that Apple does not provide interactive events about Uicontroll. Event, we consulted Github’s ideas and finally ran normally. The code is as follows:

    var cancellable: AnyCancellable?
    override func viewDidLoad() {
        super.viewDidLoad()
        cancellable = textTF.publisherEvent(.editingChanged).map(\.text).sink { (text) in
            print(text)
        }
    }

Copy the code

conclusion

Combine is still to be improved. The API provided by Common UI controls is not rich enough, and it needs to be encapsulated by itself. It also needs to provide the result returned by a global variable reference, which is not elegant. Adding the listener Control.editingChanged event triggers the KVO of the UITextField