RxSwift for iOS developers (1)

Maybe we have all heard of RxSwift, but maybe we only know the word RxSwift. Long introductions about RxSwift often make readers get lost in various concepts, but do not know how to make it work. Maybe we can change our posture. Some application scenarios will resonate with us. There are many ways to solve problems. Why not find an optimal one? RxSwift might help you.

What is ReactiveX (Reactive Extensions)

  • An API for asynchronous programming
    with observable streams

An API for asynchronous programming through observable streams (don't understand? Well, read all the examples before reading one)

  • ReactiveX is more than an API, it's an idea and a breakthrough in programming. It has inspired several other APIs, frameworks, and even programming languages.

ReactiveX is not just a simple API, it is a breakthrough of programming ideas. It has affected other APIs, frameworks, and programming languages.

it's everywhere

It is cross-platform (RxJS, RxJava, RxNET), which means mastering the idea of ​​RxSwift and learning other Rx series will be very simple.

A summary first? Summarize before you even start!

ReactiveX (Reactive Extensions) is an API for asynchronous programming through observable streams, which combines the essence of observer pattern, iterator pattern and functional programming. RxSwift is an implementation of the ReactiveX programming idea. Almost every language has an Rx[xxxx] framework, such as RxJava, RxJS, etc. Rx can be summarized as:

  • Observer mode Observable : process some data streams (very broad, can be some events, etc.) to turn them into observable object (Observable) sequences, so that observers (observers) can subscribe to these sequences;
  • Operator Operators : However, for subscribers (observer) some options (items) are not what they need (need to filter), and some options (items) need to be converted to achieve their own purposes;
  • Iterator mode Iterator : This way the values ​​in the collection or sequence can be traversed.
  • Scheduler Scheduler : In order to improve the user experience or other purposes, some operations need to be executed on a specific thread, such as UI operations need to be placed on the main thread, which involves the scheduler.

So Rx can be generalized like this, Rx = Observables + LINQ + Schedulers, where LINQ (Language Integrated Query) language integrates queries, such as those operation symbols.

Let's look at an example first: modify the user's nickname

User nickname must be composed of 3-10 characters. If the user name is invalid, a prompt will be displayed (the nickname is composed of 3-10 characters), and the modification button cannot be clicked.

func registerRx() {
    let nickNameValid = nickNameTextField.rx.text.orEmpty
        .map { (text) -> Bool in
        let tLength = text.characters.count return tLength >= 3 && tLength <= 10 } .share(replay: 1) nickNameValid .bind(to: alertLabel.rx.isHidden) .disposed(by: disposeBag) nickNameValid .bind(to: changeButton.rx.isEnabled) .disposed(by: disposeBag) changeButton.rx.tap .subscribe { (next) in print("修改昵称成功!") } .disposed(by: disposeBag) } 
 
Picture from Jianshu App

Knowledge point description

  • When installing RxSwift, RxSwift (the implementation of ReactiveX) and RxCocoa (the implementation of the iOS cocoa layer) will be installed;
  • orEmpty: mainly makes the  String?type into a  Stringtype;
  • map: It belongs to one of the Rx transformation operations. It mainly applies a function to the data emitted by the Observable, performs a certain operation, and returns the Observable processed by the function. Observable observable object, used to be subscribed by the observer (observer), so that the observer can listen to the events emitted by the Observable;
  • share(replay: 1): Only allow listening once;

At this point, still don't understand the basic concepts?

Observable

Observable literally translates to observable, it plays a pivotal role in RxSwift, and you will often deal with it throughout the use of RxSwift. If you've used RAC, it  's the Signalsame. The key point in RxSwift is how to make ordinary data or events observable, so that when some data or events change, its subscribers will be notified.

So how can some data or events become Observable?
There are many ways to create Observables in RxSwift. For example: From, never, emptyand  createetc., and more creation methods . Subscribers can receive 3 events, onNext, onErrorand  onCompleted, and each Observable should have at least one  onErroror  onCompletedevent, which onNextrepresents the flow of data when it passes to the next receiver.

func create() {
       let observable = Observable<String>.create { (observer) -> Disposable in
        observer.onNext("Hello Lefe_x, I am here!") observer.onCompleted() return Disposables.create() } observable.subscribe(onNext: { (text) in print(text) }, onError: nil, onCompleted: { print("complete!") }, onDisposed: nil).disposed(by: disposeBag) } 
 
July

Lefe_x often swipes Weibo. At the beginning, he didn't swipe Weibo, and others wouldn't see what he posted (he couldn't subscribe at this time). One day, Lefe_x wanted the knowledge he learned to help more classmates, so he registered on Weibo and started a journey of brushing Weibo (becoming a subscribeable Observable), so that others could follow him (subscribe) . Slowly, more and more people started to follow him, so that when he tweets (event stream), his fans can be reminded (notify subscribers), these reminders have different functions, such as reminding Lefe_x Published new Weibo, and some reminded Weibo to be forwarded (equivalent to  onNext, onErrorand  onCompletedevents).

Operators

After the Observable is created, it may be necessary to modify it to meet some requirements, and then operators need to be used. RxSwift provides a lot of operators. Of course, it is not necessary to master these operators one by one. You can check them when you use them. Of course, common operators must be mastered, such as  map, flatMap, create, and so filteron. see more here

Another example to relax:

This example mainly finds the strings in the array  Lefe_xand displays them on the Label.

override func viewDidLoad() {
    super.viewDidLoad()
    DispatchQueue.global().async {
        self.from()
    }
}
    
func from() {
    Observable.from(["Lefe", "Lefe_x", "lefex", "wsy", "Rx"]) .subscribeOn(MainScheduler.instance) .filter({ (text) -> Bool in return text == "Lefe_x" }) .map({ (text) -> String in return "我的新浪微博是: " + text }) .subscribe(onNext: { [weak self] (text) in self?.nickNameLabel.text = text }) .disposed(by: disposeBag) } 

The running result is:


 
Picture from Jianshu App

Yeah, wasn't this written by someone the other day? That's right, that's a #iOS knowledge collection# that was posted a few days ago, but it's just a summary, no detailed explanation. Here we mainly talk about the scheduler (Scheduler).

Scheduler Scheduler

If you want to add multi-threading capabilities to the Observable operator chain, you can specify the operator (or a specific Observable) to execute on a specific Scheduler. For the observable operator in ReactiveX, it sometimes takes a scheduler as a parameter, which can specify in which thread the observable is executed. By default, some observables are executed in the thread when the subscriber subscribes. SubscribeOn can change which scheduler the observable should execute in. ObserveOn is used to change the scheduler where notifications are sent to subscribers. In this way, the observable object can be executed in that scheduler if it wants to be executed, without constraints, and these details are not concerned by the caller. Just like GCD, you just use it, you don't have to care about how the underlying thread is created.

write at the end

The next article is going to write something about Rx doing data binding and the interaction of the network layer.

refer to



Author: Lefe
Link: https://www.jianshu.com/p/35ed80a05952
Source: Jianshu The
copyright belongs to the author. For commercial reprints, please contact the author for authorization, and for non-commercial reprints, please indicate the source.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325651879&siteId=291194637