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 GCD part 1: Thread safe singletons

Preview Singletons are entities, referenced to the same instance of a class from everywhere in your code. It doesn't matter if you like them or not, you will definitely meet them, so it's better to understand how they work. Constructing and handling a set of data doesn't seem to be a big challenge at first glance. The problems appear when you try to optimise the user experience with background work and your app starts acting weird. ??‍♂️ After decades of watching your display mostly with a blank face, you finally realize that your data isn't handled consistently by the manager because you're accessing it (running tasks on it) from multiple threads at the same time. So you really do have to deal with making your singletons thread safe. This article series is dedicated to thread handling using Swift. In the first part below you will get a comprehensive insight into som...

Kiến thức cơ bản về RxSwift

Bài viết với mong muốn cung cấp thông tin cơ bản về kiến trúc, các thuật ngữ được sử dụng phổ biến về RxSwift, giúp những lập trình viên lần đầu làm quen RxSwift sẽ trở nên dễ dàng hơn. Trong bài viết có sử dụng một số từ khóa tiếng Anh, mình xin phép sẽ giữ nguyên bản không sử dụng tiếng Việt vì có lẽ sẽ dễ hiểu hơn cho người đọc. Observable Sequences Mọi hoạt động trong RxSwift từ việc đăng ký và xử lý sự kiện đều thông qua một Observable Sequences Trong RxSwift , các kiểu dữ liệu như Arrays , Strings hoặc Dictionary sẽ được convert sang Observable Sequences . Ta có thể tạo ra "Observable Sequences" của bất kỳ kiểu đối tượng nào tuân theo Sequence Protocol của Swift Standard Library . let helloSequence = Observable.just( "Hello Rx" ) let fibonacciSequence = Observable. from ([ 0 , 1 , 1 , 2 , 3 , 5 , 8 ]) let dictSequence = Observable. from ([ 1 : "Hello" , 2 : "World" ]) Đăng ký nhận event từ ""Observable Se...

Thread safe singleton’s in Swift

What are singletons? — Singleton is design patterns which says that there should be only one instance of the class for the lifetime of the application. One the best example of Singleton is AppDelegate . How to write a singleton class ? class DefaultDict{ private var dict:[String:Any] = [:] public static let sharedManager = DefaultDict() private init(){ } public func set(value:Any,key:String){ dict[key] = value } public func object(key:String) -> Any?{ dict[key] } public func reset(){ dict.removeAll() } }   Testing singleton class under concurrent circumstances. We are going to write an example where we will set values in dict from various threads and even try to access some with different threads. When we do this we will encounter a crash. If you look closely it will be because of race condition and the crash will be on line set(value:Any,key:String) . class ViewController: UIViewController { ...