Make writing a habit together! This is the second day of my participation in the “Gold Digging Day New Plan · April More text challenge”. Click here for more details.
We previously learned the idea of RxSwit in programming, as well as the use of RX in Swift for our common controls, this paper mainly introduces the core logic of RxSwit sequence.
1. Observable sequence – Observable
Observable sequences can be finite or infinite. For example, our network requests are finite, while timers are infinite and constantly changing.
- Infinite series
let ob1 = Observable<Int>.interval(1.scheduler: MainScheduler.instance)
Copy the code
For example, we created a timer, which is an infinite sequence
- Finite sequence
let ob2 = Observable.just([1.2.3])
ob2.subscribe { (arr) in
print(arr)
} onError: { error in
print(error)
} onCompleted: {
print("completed")
} onDisposed: {
print("disposed")
}.disposed(by: disposeBag)
Copy the code
For initializing an array is to subscribe to it as it changes, and for sequence completion, destroy
- error
For incorrect subscriptions, let’s say we request an incorrect network request
URLSession.shared.rx.response(request: URLRequest.init(url: URL.init(string: "www.baidu.xx")!))
.subscribe(onNext: { (respose,data)in
}, onError:{ (error) in
print(error)
}).disposed(by: disposeBag)
Copy the code
Print the result
Sequences are created, subscribed, and destroyed, whether they are finite or infinite.
We create a sequence and look at its flow
/ / 1. To create
let ob = Observable<Any>.create{ (obserber) -> Disposable in
//3. Send signals
obserber.onNext("hello")
obserber.onError(NSError.init(domain: "NetWorkError".code: 400.userInfo: nil))
//obserber.onCompleted()
return Disposables.create()
}
/ / 2. Subscription
ob.subscribe(onNext: { (value) in
print(value)
}, onError:{ (error) in
print(error)
} , onCompleted: {
print("Subscription completed")},onDisposed: {
print("Subscription Destruction")
}).disposed(by: disposeBag)
Copy the code
Here onNext means to send a signal once, onError and onCompleted are mutually exclusive, both representing the completion of the sequence, and the flow is the same as in the diagram above.
2. The core logic of the sequence
2.1 Creating a Sequence
We perform the following callback, which is essentially a call to the closure, by passing the value onNext(). Let’s look at the creation of create
Click on to see AnonymousObservable initialization
It’s basically an initialized constructor and a real column method of Run that initializes and stores the closure subscribeHandler we pass in.
2.2 Subscription Sequence
- Continue to look at
subscribe
This method passes in a closure that returns a Disposable. Disposable is used for recycling sequences, and you can pass them in the closure onDisposed, otherwise the system will create them for you. Then create an observer, passing in a trailing closure. There are different callbacks in this closure based on the Event enumeration. It can be found that Error and complete will have disposable.Dispose (), which means to end this sequence.
asObservable()
Observable
. Create creates a sequence, and subscribe creates an observer. How do they connect? We can see the last sentence
return Disposables.create(
self.asObservable().subscribe(observer),
disposable
)
Copy the code
For asObservable ()
Agreement ObservableConvertibleType defined in this method, we follow the observables sequence of this agreement
Just like the cast of the type in our OC for example, if all our classes in OC inherit from NSObject then all our subclasses can convert to NSObject,
The self we return, AnonymousObservable, is also an Observable
, so we can subscribe.
subscribe(observer)
In this case, we subscribe from the sequence we created to the Observe sequence, and then execute the callback in the closure. Simply sending the event triggers the callback, making it reactive.
We didn’t find an implementation of SUBSCRIBE in the sequence AnonymousObservable, but it inherits its parent Producer
Producer
We overwrote the Subscribe method of Observale by calling our own run method, passing in the observer we passed outside. Create an AnonymousObservableSink object that holds an Observer, and then call the object’s run method to pass in self, which is observable. The AnonymousObservableSink class links observables to Observer observables and functions as a bridge between events.
sink.run
Through business sinking, the division of labor is more clear
This will callback the callback of the sequence Observe that we created earlier, so the callback of the sequence will be triggered on the first subscription. Continue to see AnyObserver (self)
When we initialize the construction here, we create a structure AnyObserver that holds a message to the AnonymousObservableSink. On function.
Save our AnonymousObserver event event
2.3 Sending Signals
According to the above analysis, the callback of subscribeHandler will go through when subscribing. We called obserber.onNext(“hello”) inside
AnyObserver is first called to follow the protocol on method, that is, to call back the event event, we passed in the event event. Next, with our element parameter. Our way on doing the AnonymousObservableSink. On so will enter the following method
Self.forwardon (event) This is also the core code to execute because AnonymousObservableSink inherits Sink and encapsulates it
Where self._observer is the observer we initialized to save: AnonymousObserver, which is the closure callback that will be called when we initialized AnonymousObserver
3. Summary
When the sequence is created, an anonymous sequence AnonymousObservable is created to save subscribeHandler. An observer AnonymousObserver is created and eventHandler is saved. The run method is called to execute the subscribeHandler callback. The sending signal calls the onCore of the observer AnonymousObserver via onNext() and so on for the _eventHandler(event) event callback. The flow chart is as follows: