Skip to main content

COMBINE vs RXSWIFT : Giới thiệu Combine

Shai MishaliHôm nay, tôi sẽ giới thiệu một frame work được Apple ra mắt vào năm 2019 tên là Combine, và chỉ ra sự khác biệt chính với RxSwift. Có lẽ con đường tốt nhất để bắt đầu là đọc định nghĩa Combine của Apple :

"A unified, declarative API for processing values overtime."

Tôi chắc rằng, đó là một định nghĩa quen thuộc, bởi vì như đã nói trước đây, bài viết này chúng ta sẽ nói về các tính năng giống và khác nhau giữa Combine và RxSwift.

Chúng ta sẽ bắt đầu bằng ba thuộc tính chính của Combine:

. Generic
. Type safe
. Composition first

Apple nói rằng khái niệm Combine rất dễ hiểu và đơn giản để hiểu và sử dụng, nhưng khi kết hợp lại chúng sẽ cho phép thực hiện những điều phức tạp và thú vị hơn.
Vào trong Combine chúng ta sẽ tìm thấy :

. Publishers
. Subscribers
. Operators

Publishers

Publisher là một phần của Combine's API. Chúng định nghĩa cách mà các giá trị và các lỗi được tạo ra.
Chúng là kiểu giá trị, trong Swift, Structs.
Publishers cho phép đăng ký một Subscribers, cho phép chúng ta lần lượt nhận những giá trị chúng phát ra.

protocol Publishers {
    associatedtype Output
    associatedtype Failure: Error

    func subscribe<S: Subscriber>(_ subscriber: S) 
        where S.input == Output, S.Failure == Failure
} 
 
Subscribers

Subscribers là một khía cạnh khác của publishers. Chúng nhận giá trị thông qua stream và từ đấy chúng có thể biến đổi thành loại tham chiếu Reference types, như classes:

protocol Subscriber {
    associatedtype Input
    associatedtype Failure: Error

    func receive(subscription: Subscription)
    func receive(_ input: Input) -> Subscribers.Demand
    func receive(completion: Subscribers.Completion<Failure>)

}
  
The reminds me of something ...

Combine vs RxSwift: Sự khác biệt 

Khả năng tương thích hiện tại:
Đầu tiên, Combine không hỗ trợ cho hệ thống iOS cũ hơn iOS 13 / macOS Catalina.
RxSwift làm việc với iOS 8 trở lên.

Error management
Nhìn vào protocol đặc biệt Observable, chúng ta sẽ thấy những khác biệt đầu tiên.

Trong Combine, mọi Publisher cần kiểu đặc biệt cho error, Trong RxSwift, Observables không định nghĩa một kiểu dữ liệu lỗi, do đó chúng ta có thể sử dụng bất kì kiểu lỗi tại bất kì thời điểm nào. Điều này làm RxSwift's Observables dễ dàng sử dụng, từ đó bạn không cần suy nghĩ về kiểu dữ liệu của lỗi lúc khởi tạo. Măt khác, điều này có nghĩa bạn sẽ phải cẩn thận khi quản lý lỗi của chính bạn.

Với Combine, nếu stream của bạn không có một kiểu dữ liệu cho errors, bạn có thể mark nó với kiểu Never.

Performance
RxSwift là một framework tối ưu, còn Combine được xây dựng bởi các kĩ sư của Apple, những người tập trung hoàn toàn 100% vào hiệu suất.
Như chúng ta có thể thấy trên blog Flawless iOS, trong cùng 1 công việc, Combine có hiệu suất nhanh hơn rất nhiều:

Operators
Combine và RxSwift có rất nhiều toán tử làm những công việc tương tự, nhưng vơí tên khác nhau.
Cảm ơn đồ thị được tạo bởi Shai Mishali đã giúp ta link tất cả toán tử với những tên khác nhau.



Mã nguồn mở
Một thành phần quan trọng mà chúng ta đề cập trước là Combine không phải là một dự án mã nguồn mở,

DisposeBag
Bạn có lẽ đã quen thuộc với bộ quản lý bộ nhớ của RxSwift: DisposeBag. Thay vì việc lưu mỗi subscription riêng biệt và kết thúc chúng khi mà controller hoặc class deinit, chúng ta đơn giản chỉ cần viết .disposed(by: disposeBag) và framework sẽ phát hiện deinit và huỷ bỏ tất cả Rx dependencies.
Combine không có bất cứ thứ gì tương tự DisposeBag. 

UI Framework
Bên trong một framework reactive chúng ta cần một vài cách để  link luồng reactive tới view và ngược lại. Giải pháp của RxSwift's là RxCocoa.



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...

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 { ...

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...