Skip to main content

RxSwift: Trait trong RxSwift - RxCocoa


Mở đầu:


Ở bài viết này, chúng ta sẽ tìm hiểu về RxCocoa. Để thuận tiện cho việc tìm hiểu, các bạn có thể theo dõi bài viết trước đó để có thể nắm được các đặc điểm của TraitSide Effect tại đây.

I. Giới thiệu:


  • RxCocoa là một thư viện được xây dựng trên nền tảng là RxSwift và nó cũng chính là một phần của RxSwift.
  • RxCocoa thêm các phần mở rộng (extension) vào các thành phần UI của iOS giúp cho chúng ta có thể subscribe để lắng nghe các sự kiện đến từ UI.
Ví dụ: Để lắng nghe sự kiện ON/OFF từ một UISwicth, chúng ta có thể subscribe thông qua phần mở rộng được cung cấp từ RxCocoa đó là .rx.isOn.

toggleSwitch.rx.isOn
  .subscribe(onNext: { enabled in
    print( enabled ? "it's ON" : "it's OFF" )
  }
RxCocoa bao gồm các thành phần chính:
  • Driver.
  • ControlProperty.
  • ControlEvent.

II. Driver:


Driver là một thành phần của RxCocoa và là một Trait được hoàn thành đầy đủ nhất. Do Driver là một Observable đặc biệt với những ràng buộc của Trait nên nó cũng sẽ mang những đặc điểm sau:
  • Không tạo ra lỗi.
  • ObserveSubscribe trên Main Scheduler.
  • Có chia sẻ Side Effect.
Driver hoạt động tương tự như Observable, ngoại trừ những điểm khác biệt:
  • Observable thì có thể thay đổi Thread tuỳ theo cách thực thi của nó. Ví dụ, khi gọi API thì sẽ bị đẩy xuống Background Thread
  • Driver luôn thục hiện trên Main Thread và không emit ra Error nên thích hợp làm việc với UI.

III. ControlEvent:


  • ControlEvent là một phần của Observable/ObservableType. Nó đại diện cho các sự kiện của các thành phần UI.
  • ControlEvent cho phép chúng ta lắng nghe những sự kiện thay đổi tới từ các UIComponent ví dụ như UIButton được bấm, UITextField được nhập text từ người dùng,...
  • Do có thể theo dõi và nhận các sự kiện của UIComponent thông qua ControlEvent nên chúng ta có thể không cần tạo các IBAction trong source code mà vẫn có thể handle được các sự kiện đến từ UI. Điều đó giúp cho source code trở nên gọn hơn và dễ dàng bảo trì.
Ví dụ về ControlEvent của UIButton:
import UIKit
import RxSwift
import RxCocoa

class ViewController: UIViewController {
    @IBOutlet weak var blueButton: UIButton!
    
    let disposeBag = DisposeBag()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        blueButton.rx.tap.asDriver()
            .drive(onNext: { _ in
                print("Button tap !")
            })
            .disposed(by: disposeBag)
    }
}
Button tap !
Button tap !
Button tap !
Button tap !
Button tap !

IV. ControlProperty:


  • ControlProperty là một phần của Observable/ObservableType. Nó đại diện cho các property của các thành phần UI.
  • ControlProperty giúp chúng ta có thể thay đổi giá trị của một property trong UIComponent.
  • Các ControlPeroperty của các thành phần giao diện hầu hết đã được cung cấp bởi RxCocoa.
Ví dụ về ControlProperty của UISegment:
import UIKit
import RxSwift
import RxCocoa

class ViewController: UIViewController {
    @IBOutlet weak var greenSwitch: UISwitch! // default is ON
    @IBOutlet weak var blueButton: UIButton!
    
    let disposeBag = DisposeBag()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        blueButton.rx.tap.asDriver()
            .map { _ in
                return false
            }
            .drive(greenSwitch.rx.isOn) // change UISwicth's state to OFF
            .disposed(by: disposeBag)
    }
}
  • Trong ví dụ, greenSwitch có trạng thái mặc định là ON, tức là thuộc tính isOn của UISwicth có giá trị mặc định là true.
  • Sau khi được bấm , blueButton sẽ phát ra một element có kiểu dữ liệu là Void, sau đó operator .map giúp chúng ta biến đổi giá trị của element từ kiểu Void thành kiểu Bool với giá trị là false.
  • ControlProperty giúp chúng ta set giá trị mới là false cho property isOn của greenSwicth. Điều đó giúp greenSwicth thay đổi trạng thái từ ON -> OFF.

V. BindingProperty:


Ngoài việc sử dụng các ControlProperty, chúng ta có thể tạo các BindingProperty để binding dữ liệu.
// tạo một binding property cho UISwict nằm trong extention của Reactive
extension Reactive where Base: UISwitch {
    var customSwitchBinding: Binder<Bool> {
        return Binder(base) { mySwitch, newState in
            mySwitch.isOn = newState
            print("State has been changed !")
        }
    }
}
import UIKit
import RxSwift
import RxCocoa

class ViewController: UIViewController {
    @IBOutlet weak var greenSwitch: UISwitch!
    @IBOutlet weak var blueButton: UIButton!
    
    let disposeBag = DisposeBag()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        blueButton.rx.tap.asDriver()
            .map { _ in
                return false
            }
            .drive(greenSwitch.rx.customSwitchBinding) // Sử dụng binding property
            .disposed(by: disposeBag)
        
    }
}
State has been changed !

Tài liệu tham khảo:


Comments

Popular posts from this blog

Swift Tool Belt, Part 1: Adding a Border, Corner Radius, and Shadow to a UIView with Interface Builder

During my iOS work, I’ve assembled a set of code that I bring with me on every iOS project. I’m not talking about large frameworks or CocoaPods here. These are smaller Swift extensions or control overrides that are applicable to many projects. I think of them as my tool belt. In this post, I’ll show you an extension that will add a border, a corner radius, and a shadow to any UIView, UIButton, or UILabel and allow you to preview what it will look like in Interface Builder. Back in 2014, I wrote a blog post on Expanding User-Defined Runtime Attributes in Xcode where I added a border, corner radius, and shadow to a UIView using Interface Builder’s user-defined runtime attributes. This solution had no type checking—you had to type the property you wanted to modify by hand and often had to look up what it was called. You also had to run your project in order to see the effect of the runtime attribute. Starting with Xcode 6 , there is a new mech...

Alamofire vs URLSession

Alamofire vs URLSession: a comparison for networking in Swift Alamofire and URLSession both help you to make network requests in Swift. The URLSession API is part of the foundation framework, whereas Alamofire needs to be added as an external dependency. Many  developers  doubt  whether it’s needed to include an extra dependency on something basic like networking in Swift. In the end, it’s perfectly doable to implement a networking layer with the great URLSession API’s which are available nowadays. This blog post is here to compare both frameworks and to find out when to add Alamofire as an external dependency. Build better iOS apps faster Looking for a great mobile CI/CD solution that has tons of iOS-specific tools, smooth code signing, and even real device testing? Learn more about Bitrise’s iOS specific solutions! This shows the real power of Alamofire as the framework makes a lot of things easier. What is Alamofire? Where URLSession...

Frame vs Bounds in iOS

This article is a repost of an answer I wrote on Stack Overflow . Short description frame = a view’s location and size using the parent view’s coordinate system ( important for placing the view in the parent) bounds = a view’s location and size using its own coordinate system (important for placing the view’s content or subviews within itself) Details To help me remember frame , I think of a picture frame on a wall . The picture frame is like the border of a view. I can hang the picture anywhere I want on the wall. In the same way, I can put a view anywhere I want inside a parent view (also called a superview). The parent view is like the wall. The origin of the coordinate system in iOS is the top left. We can put our view at the origin of the superview by setting the view frame’s x-y coordinates to (0, 0), which is like hanging our picture in the very top left corner of the wall. To move it right, increase x, to move it down increase y. To help me remember bound...