Understanding RxSwift: Why use RxSwift (part 1)
Understanding RxSwift: Implementation Principles (part 2)
RxSwift: MVVM (3)
Understanding RxSwift: Unit Testing (Part 4)
RxSwift is a framework that helps simplify asynchronous programming. It is the Swift version of ReactiveX (Rx).
RxSwift extends the observer mode by allowing you to freely combine multiple asynchronous events without worrying about threads, synchronization, thread safety, concurrent data, and I/O blocking.
Basic concepts and usage
RxSwift is functional responsive programming. It is programming by building functions that manipulate sequences of data and then respond to those sequences. It combines functional and responsive programming.
Functional programming
Functional programming requires us to pass functions as arguments or return them as return values. We can combine different functions to get the result we want.
Here’s an example:
// The whole schoolletAllStudents: [Student] = getSchoolStudents() //let gradeThreeClassTwoStudents: [Student] = allStudents
.filter { student inStudent. Grade = = 3 && student. The class = = 2} / / print class two of the three years from high to low grades gradeThreeClassTwoStudents. Sorted {student0 student1in student0.score > student1.score }
.forEach { student in print("score: \(student.score), name: \(student.name)")}Copy the code
Responsive programming
Reactive programming is programming with asynchronous data streams. Anything can be a data stream, such as user input, click events, timers, network requests, etc., listening to the data stream and responding accordingly.
On this basis, you can use various functions to combine, create, and filter these data streams, which is called functional responsive programming.
// Assume that the user clicks the button three times between entering the page and leaving the pageletTaps: observables < Void > = button. The rx. Tap. AsObservable () / / after each click pop-up prompt box taps. The subscribe (onNext: {showAlert ()})Copy the code
Observable
The next event indicates the launch of new data, the complete event indicates the launch is complete, and the error event indicates an exception
For example, launch 10 numbers starting from 0
let numbers: Observable<Int> = Observable.create { observer -> Disposable in
observer.onNext(0)
observer.onNext(1)
observer.onNext(2)
observer.onNext(3)
observer.onNext(4)
observer.onNext(5)
observer.onNext(6)
observer.onNext(7)
observer.onNext(8)
observer.onNext(9)
observer.onCompleted()
return Disposables.create()
}
Copy the code
Observer
An observer object that listens for events and responds to them.
For example, the Observable above sends 10 numbers and creates an Observer that listens and prints the received data
numbers.subscribe(onNext: { number in
print(number)
}, onError: { error in
print(Error: \ "(error. LocalizedDescription)")
}, onCompleted: {
print("Mission accomplished.")})Copy the code
Operator
Operator used to create new Observables or transform groups of existing Observables.
For example, the filter operator filters an Observable based on criteria. The following code filters numbers greater than 10
let disposeBag = DisposeBag()
Observable.of(2, 30, 22, 5, 60, 1)
.filter { $0 > 10 }
.subscribe(onNext: { print($0) })
.disposed(by: disposeBag)
//output
30
22
60
Copy the code
Demo
The official Demo beeth0ven. Making. IO/RxSwift – Chi…
Why use RxSwift
The code is clear and concise, easy to read and maintain
Using Target Action as an example, compare the traditional implementation with the RxSwift implementation:
Button. addTarget(self, action:);#selector(buttonTapped), for: .touchUpInside)
func buttonTapped() {
print("button Tapped")}Copy the code
// RxSwift
button.rx.tap
.subscribe(onNext: {
print("button Tapped")
})
.disposed(by: disposeBag)
Copy the code
The RwSwift approach makes callback handling very simple.
Similarly, RxSwift can replace asynchronous callbacks such as proxy, notification, KVO, concurrent events, etc. More see the official documentation for example: beeth0ven. Making. IO/RxSwift – Chi…
Provides data view synchronization for MVVM
In MVVM architecture, data binding is used to separate data from view. When the data is updated, the view is automatically updated. When the view changes, it is automatically fed back to the data.
Since iOS doesn’t provide good data and view binding, we need third-party libraries to do this, and RxSwift is a good choice.
RxSwift provides an elegant way to make synchronization between views and ViewModels easy without writing a lot of cumbersome imperative binding code.
Note: RxSwift does not have to work with MVVM. In MVC, data view binding can also be used to quickly complete UI development.
Declarative programming, focused on processing data logic
RxSwift introduced the declarative programming paradigm, which simply tells the system “what” rather than “how” to compute. Declarative programming lets developers focus on the implementation of business logic instead of tedious View operations.
In declarative programming, a process starts with a data source, transforms the data, processes it, transforms it, and presents it in a view. In general, data sources get the original data through the callback interface. The original data cannot be used directly. It usually needs to be processed and transformed according to the business to generate data in a new format, and finally bound to the view. In this process, RxSwift uses a number of operators to perform various types of data transformations and bind data to views.
Good testability
We know that unit tests for MVC are difficult to write, and one of the reasons is that functions can manipulate views directly, making testing and validation difficult.
RxSwift binds data to the view for synchronization, assumes the view operation, data updates automatically synchronize the view, developers only need to write the data processing logic, so that we can test the data.
summary
Functional responsive programming is becoming more popular among developers because it makes complex asynchronous code easier to write and understand and provides data synchronization capabilities for MVVM. In particular, RxSwift provides data synchronization that makes synchronization between views and ViewModels easy and complements MVVM. RxJs is not a popular library in the React stack because React does not require third-party libraries to provide data binding. So RxJs only has the advantage of simplifying asynchronous events.
Of course, RxSwift also has some disadvantages, including high learning cost, strong invasion, suitable for complex asynchronous data flow scenarios, not suitable for simple services, etc. RxSwift introduces new concepts and ideas, such as functional, responsive, and declarative programming, which are very different from traditional programming methods and require a lot of time to become familiar with the new development mode. Moreover, in APP development, the process of many scenarios is relatively simple and there is not much interaction. Notifications and blocks are enough to solve the problem.
conclusion
In this article, we introduce some basic concepts and usage of RxSwift, and give four reasons why you should use RxSwift.
I hope this article helps you understand RxSwift, so get started.
The next article in this series will examine the implementation of RxSwift and write a simple version of RxSwift to help you understand its inner workings and implementation.
The resources
Reactive Programming for RxSwift