RxSwift Perhaps we have heard, but perhaps only know RxSwift the word, long-winded about the RxSwift introduction often makes the reader lost in various concepts, but do not know how to let it reach out. Perhaps we can change a posture, some application scenarios will resonate with us, the way to solve the problem by a lot, why not find an optimal? Rxswift may help you.
What is Reactivex (reactive Extensions)
- An API for asynchronous programming
With observable streams
An API for asynchronous programming with observable streams (not understood?) Well, read all the examples before reading another article)
- 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 only an API so simple, it is a breakthrough in the idea of programming. It has affected other api,frameworks, as well as programming languages.
It's everywhere.
It is cross-platform (rxjs,rxjava,rxnet), which means mastering RxSwift this idea, learning the other RX series will be very simple.
Let's start with a summary. It's not the beginning!
Reactivex (reactive Extensions) is an API for asynchronous programming through observable streams that combines the essence of observer patterns, iterator patterns, and functional programming. RxSwift is an implementation of Reactivex programming ideas, and almost every language will have a rx[xxxx] framework, such as RXJAVA,RXJS. Rx can be summarized as:
- Observer Pattern Observable: Some data streams (very wide, can be events, etc.) are processed to make them a sequence of observable objects (Observable) so that observers (Observer) can subscribe to these sequences;
- operator Operators: However, for subscribers (Observer) some options (items) are not needed (filter), and some options (items) need to be converted to achieve their own purposes;
- iterative mode Iterator: So that 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 placed on specific threads to perform, such as UI operations need to be put into the main thread, which involves the scheduler.
So rx can generalize like this, Rx = observables + LINQ + schedulers, where LINQ (Language Integrated Query) language integrates queries such as those that manipulate symbols.
Let's take a look at the example: Modify user Nickname
User nickname must be composed of 3-10 characters, the user name is not valid display prompt (nickname consists of 3-10 characters), and the Modify button is not clickable.
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)}
Pictures from the simple book app Knowledge point description
- Installing RxSwift installs the RxSwift (Implementation of Reactivex) and Rxcocoa (Implementation of the iOS cocoa layer);
- Orempty: Mainly make
String? type into type String ;
- Map: It belongs to one of the Rx transformation operations, which mainly applies a function to the data emitted by the Observable, performs some operation, and returns the Observable that have been processed by the function. Observable observable object that is used by the Observer (Observer) to subscribe so that observe can listen to Observable events;
- Share (REPLAY:1): only allowed to listen once;
Here, you don't know the basic concept? Observable
Observable literal translation is observable, it plays a pivotal role in RxSwift, and you will often deal with it throughout the course of RxSwift's use. If you've ever used a RAC, it's the Signal same. The key point in RxSwift is how to turn ordinary data or events into observable, so that when certain data or events change, they are notified to subscribers.
How can you make certain data or events become Observable?
There are a number of ways to create Observable in RxSwift. For example: From ,, never , empty and create so on, more ways to create. Subscribers can receive 3 events, onNext onError and onCompleted , each Observable should have at least one onError or onCompleted event that onNext represents the data stream when it passes to the next recipient.
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) }
Juli
Lefe_x often brush Weibo, and at first he did not brush his tweets, and no one else could see what he was sending (and he was not subscribed). One day, Lefe_x wanted to let himself learn the knowledge to help more students, he registered Weibo, began to brush the microblog journey (become a Observable), so that others can focus on him (subscribe). Slowly, more and more people began to pay attention to him, so that when he tweets (stream), its fans can be reminded (notify subscribers), these reminders have different functions, such as some is to remind lefe_x to release the new Weibo, some reminders Weibo was forwarded (equivalent onNext , onError and onCompletedevent).
Operators operator
When Observable is created, you may need to modify it to meet certain requirements, and you need to use the operator. RxSwift provides a lot of operators, of course, not necessarily one by one master these operators, use the time to check, of course, the common operators must be mastered, such as,, map flatMap , and create filter so on. See more here
One more example to relax:
This example mainly looks up the string in the array Lefe_x and displays it on the Label.
Override Func Viewdidload () {super.viewdidload () Dispatchqueue.global (). async {self.fr Om ()}} 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 " My Sina Weibo is: "+ text}". Subscribe (onNext: {[self] (text) in self?. Nicknamelabel.text = text}). Disposed (by:disposebag)}
The result of the operation is:
Pictures from the simple book app
Well, isn't that something someone wrote in the last few days? Yes, that was a few days ago #iOS知识小集 #, but where is just a summary, no detailed description. Here is the main point of the Scheduler (Scheduler).
Scheduler Scheduler
If you want to add multithreaded functionality to the Observable operator chain, you can specify that the operator (or a specific Observable) be executed on a specific scheduler (Scheduler). For the observable object operator in Reactivex, it sometimes carries a scheduler as a parameter, which allows you to specify which thread the observable object executes in. By default, some observable objects are executed in the same thread that the Subscriber subscribes to. Subscribeon can change the observable object to be executed in that scheduler. Observeon is used to change the scheduler in which notifications are sent to subscribers. This makes it possible for an observable to execute in that dispatcher in that scheduler, unconstrained, and these details are not of interest to the caller. Like GCD, you just use, the bottom thread is how to create, you don't have to care.
Written in the last
The next article intends to write about Rx doing data binding and network layer interaction.
Reference
- Reactivex
- RxSwift Learning Guide Index
- Reactivex document Chinese Translation
- Realm
Lefe
Links: https://www.jianshu.com/p/35ed80a05952
Source: Pinterest
Copyright belongs to the author. Commercial reprint please contact the author for authorization, non-commercial reprint please specify the source.
RxSwift for IOS Developers (i)