RAC makes our OC development process more convenient, faster and more developer-oriented. Does Swift, apple’s main push, have such a convenient third-party framework? Of course, the answer is yes, RxSwift, to meet our needs, let’s take a preliminary experience of RxSwift.

First we have a simple requirement: listen for changes in the text of the UITextField. Conventional methods, we can think of many, such as proxy, notification.

  • notice
override func viewDidLoad() {super viewDidLoad () / / add notification NotificationCenter default. The addObserver (self, the selector:#selector(textChange), name: UITextField.textDidChangeNotification, object: self.textField!)
}
    
@objc func textChange() {// Do the specific operation in the actual developmentprint("\(textField.text!) ")}deinit() {
     NotificationCenter.default.removeObserver(self)
}
Copy the code
  • The agent
class ViewController: UIViewController, UITextFieldDelegate {
    @IBOutlet weak var textField: UITextField!

    override func viewDidLoad() { super.viewDidLoad() textField.delegate = self } func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString String: string) -> Boolprint("\(textField.text)")
        return true}}Copy the code

Requirement implementation process is quite simple, of course, in the actual development of certainly not only a print operation, the conventional method to solve our needs, so RxSwift is how to solve our needs?

  • RxSwiftListening to theUITextField
func setupTextFiled() {
   self.textFiled.rx.text.orEmpty
     .subscribe(onNext: { (text) in// Do specific operations in actual developmentprint(text)
     })
     .disposed(by: disposeBag)
}
Copy the code

Let’s compare the general methods such as notification and proxy with RxSwift: 1. Notifications need to be added to the notification center, and we need to add a callback method textChange to listen for text changes; 2. The proxy needs to comply with the proxy protocol and implement proxy methods to monitor text changes; 3.RxSwift chain programming, direct operation of textField, more oriented to developers.

Of course, this simple requirement does not show the power and convenience of RxSwift. It is only the beginning of a simple experience. Let’s have more experience of RxSwift to feel whether it is really convenient:

A, notifications,

  • Since I mentioned it at the beginningnotice“Started with notifications
//MARK: - Notify funcsetupNotification(){
    NotificationCenter.default.rx.notification(UIResponder.keyboardWillShowNotification)
        .subscribe(onNext: { (noti) in
            print(Noti)}).disposed(by: disposeBag)} // To save space, the code for notification has been written above, and will not be reused hereCopy the code

Button click

//MARK: - RxSwift application -button response funcsetupButton() {
    self.button.rx.tap
        .subscribe(onNext: { () in
            print("Stop ordering me!!"Disposed (by: disposeBag)} //MARK: -button Conventional response funcsetupBtn() {
    btn.addTarget(self, action: #selector(btnDidClick(_:)), for: UIControl.Event.touchUpInside)
}

@objc func btnDidClick(_ sender: UIButton) {
    print("Point me again, I am anxious with you!")}Copy the code
  • We are no longer required to goaddTargetDon’t be afraid to forget@objc;

Third, UIScrollView

//MARK: -rxSwift application -scrollView funcsetupScrollerView() {
    scrollView.rx.contentOffset
        .subscribe(onNext: { [weak self](content) inself? .view.backgroundColor = uicolor. init(red: content.y / 255 * 0.7, green: content.y / 255 * 0.4, blue: Disposed (by: disposeBag)} //MARK: Delegate = self; func scrollViewDidScroll(_ scrollView: UIScrollView) {print("\(scrollView.contentOffset)")
    letY = scrollView. ContentOffset. Y self. The backgroundColor = UIColor (red: y / 255 * 0.7, green: y / 255 * 0.4, blue: Y / 255 * 0.1, alpha: 1.0)}Copy the code
  • With theRxSwiftWe don’t have to care anymoreThe agentThere is no need to tangle with which proxy method to use, one line of code.

Four, gestures

//MARK: - gesture - RxSwift funcsetupGestureRecognizer() {let tap = UITapGestureRecognizer()
    self.label.addGestureRecognizer(tap)
    self.label.isUserInteractionEnabled = true
    tap.rx.event.subscribe(onNext: { (tap) in
        print(tap.view)}). Disposed (by: disposeBag)} //MARK: - gesture - conventional notation funcsetupGesture() {
    label.isUserInteractionEnabled = true
    let tapGesture = UITapGestureRecognizer(target: self, action: #selector(tap))
    label.addGestureRecognizer(tapGesture)
}

@objc func tap() {
    print("Label is ready to click")}Copy the code
  • Embarrassed, as if this doesn’t make us feel convenient, there’s nothing to talk about, so force one,So easy, mom doesn't have to worry about me forgetting @objc anymore.wit

Five, the KVO

//MARK: -rxSwift -kvo funcsetupKVO() {
    self.person.rx.observeWeakly(String.self, "name")
        .subscribe(onNext: { (value) in
            printPrompt (value as Any)}).disposed(by: disposeBag)} //MARK: -kvoforKeyPath: "name", options:. New, context: nil) override func observeValue(forKeyPath keyPath: String? , of object: Any? , change: [NSKeyValueChangeKey : Any]? , context: UnsafeMutableRawPointer?) {print("\((change! [NSKeyValueChangeKey.newKey])!) "Person.removeobserver (self,forKeyPath: "name")}Copy the code
  • Too bad,RxSwiftCan’t be freed without removing the observer? Does not exist; Should we care about removal? Don’t need;KVOWhat is a trilogy? Clouds also.

At the end of the day, these are just some experiences of writing simple swift in general versus RxSwift, which gives us the feeling that. The button doesn’t need us to write any more, it needs to pop out and add a method to addTarget; There is no need to set up the proxy, no need to care about notifications, whether KVO releases….. in deinit RxSwift has more, more powerful functions, waiting for us to explore, we go to experience everything sequence, experience the original code can also write so simple feeling.