Understand RxSwift: Why use RxSwift (a)

RxSwift is a framework that can help us simplify asynchronous programming, it is ReactiveX (abbreviation: Rx) version of Swift.

RxSwift expand the observer mode, it can help you freely combine multiple asynchronous events, without the need to care about thread synchronization, thread-safe, concurrent data and I / O blocked.

The basic concept and use

RxSwift reactive programming function belongs. It is by constructing function operation data sequence, and then made programmatically respond to these sequences. It combines the function of programming and in response to programming.

Functional Programming

Functional programming we need passed as a parameter to a function or returned as a return value. We can get the desired results by different combinations of functions.

Look at an example:

// 全校学生
let allStudents: [Student] = getSchoolStudents()

// 三年二班的学生
let gradeThreeClassTwoStudents: [Student] = allStudents
    .filter { student in student.grade == 3 && student.class == 2 }
    
// 由高到低打印三年二班的学生成绩
gradeThreeClassTwoStudents
    .sorted { student0, student1 in student0.score > student1.score }
    .forEach { student in print("score: \(student.score), name: \(student.name)") }

Reactive programming

Reactive programming is programmed using an asynchronous data stream. Everything can be a stream of data, such as user input, click on the event, timers, and other network requests, monitor data streams and make the appropriate response.

On this basis, a variety of functions to be used in combination, create a filtered data stream, which is reactive programming function.

// 假设用户在进入页面到离开页面期间,总共点击按钮 3 次

// 按钮点击序列
let taps: Observable<Void> = button.rx.tap.asObservable()

// 每次点击后弹出提示框
taps.subscribe(onNext: { showAlert() })

Observable

Observable objects, used to transmit data, next event indicates that the launch of new data, complete event indicates that the launch is completed, error represents an exception

Example, starting from 0 are sequentially transmitting digital 10

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()
}

Observer

Observer objects used to monitor events and respond.

Example, the above Observable sent 10 numbers here to create an Observer, listen and print data received

numbers.subscribe(onNext: { number in
    print(number)
}, onError: { error in
    print("发生错误: \(error.localizedDescription)")
}, onCompleted: {
    print("任务完成")
})

Operator

Operator, to create a new combination of transform Observable object or original Observable.

Example, filter operator is filtered in accordance with conditions of a Observable, the following code is the number of the filter 10 is greater than

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

Demo

官方 Demo
https://beeth0ven.github.io/RxSwift-Chinese-Documentation/content/first_app.html

Why use RxSwift

Code is clear and concise, easy to read, easy to maintain

Target Action is to contrast the traditional implementation and realization of RxSwift:

// 传统实现方法
button.addTarget(self, action: #selector(buttonTapped), for: .touchUpInside)

func buttonTapped() {
    print("button Tapped")
}
// RxSwift
button.rx.tap
    .subscribe(onNext: {
        print("button Tapped")
    })
    .disposed(by: disposeBag)

RwSwift way to make the callback process becomes very simple.

The same, RxSwift can replace some asynchronous callbacks, such as proxy, notice, KVO, concurrent events. See more examples of official documents: https://beeth0ven.github.io/RxSwift-Chinese-Documentation/content/why_rxswift.html#target-action

Provide synchronization for the data view MVVM

In MVVM framework, the use of data binding, so that data with a view to separate, when the data is updated automatically to update the view, and the view changes and automatically fed back to the data, the data is the dominant factor, which would allow focused on data logic dealing with.

Since iOS does not provide a good view data binding, we need to use third-party libraries to achieve this function, RxSwift is a good choice.

RxSwift provides an elegant way to keep synchronization between the View and the ViewModel easier to avoid writing a lot of tedious imperative binding code.

Note: RxSwift not have to match MVVM used in MVC, the same data can be used to bind view, quickly complete UI development.

Declarative programming, to focus on the data processing logic

RxSwift brought a declarative programming paradigm, you only need to tell the system need to calculate the "what" rather than "how" to calculate. Declarative programming allows developers to focus View from the tedious operation freed to focus on business logic implementation.

In declarative programming, a process starting from a data source, transform the data, the data to do some processing, conversion, show up on the final view. General data source is transferred via an interface to get the original data, the original data can not be directly used, often require conversion processing according to the service, generating new data format, and finally bound to the view, when data is updated, the view synchronized. In this process, RxSwift use of the various operators, various types of data conversion is completed, and the binding data and a view.

Good testability

We know that MVC unit test difficult to write, one of the reasons is the view function may operate directly, resulting in testing and verification difficult.

RxSwift bound data and view synchronization, took the view operation, data is automatically synchronized view after the update, developers only need to write data processing logic, allowing us to test the data.

summary

Function reactive programming more and more developers welcome, the reason is that it's a complex asynchronous code easier to write and understand, and provide data synchronization for MVVM. In particular RxSwift bring data synchronization, so that the synchronization between the View and the ViewModel simple, nicely complement MVVM, the front React technology stack, RxJs is not a common library, because React do not need third-party libraries It provides data binding, so the only advantage RxJs is to simplify asynchronous events.

RxSwift course, there are some disadvantages, including high cost study, invasive, suitable for asynchronous data streams of complex scenes, and the like are not suitable for simple operations. RxSwift bring new concepts and ideas, such as functional, reactive programming, declarative programming, with the traditional way of programming quite different, it takes a lot of time to become familiar with new development model. APP and development, many of the scenes process is relatively simple, not much interaction with the notification, block, etc. have been enough to solve the problem.

to sum up

In this article, we introduce some basic concepts and methods of use RxSwift, and gives four reasons why you want to use RxSwift.

Hopefully this article will help you understand RxSwift, hurry up with it.

The next in this series will analyze the realization of the principle RxSwift, and write with a simple version of the RxSwift, help you really understand its internal operating procedures and implementation principle.

Reference material

RxSwift Chinese document
Why Reactive Programming?

Guess you like

Origin blog.csdn.net/weixin_34101229/article/details/90821891