RxSwift chapter
- first
- Sequential response logic
- Sequence types
- The operator
- Scheduler – Scheduler (1)
- Scheduler – Scheduler (2)
- Common sequence
- Subject is both offensive and defensive
- MVVM bidirectional binding
RxSwift profile
RxSwift is an important member of the ReactiveX family, which stands for Reactive Extensions and is commonly abbreviated as Rx. ReactiveX defines Rx as a programming interface that uses observable data streams for asynchronous programming.
**ReactiveX is more than just a programming interface, it is a breakthrough in programming thought that has influenced many other libraries and frameworks as well as programming languages. It extends the observer mode, allowing you to freely combine multiple asynchronous events without worrying about threads, synchronization, thread safety, concurrent data, and I/O blocking.
RxSwift trial
1. The button events
func setupButton() {
self.button.rx.tap.subscribe(onNext: { () in
print("Click here.")
})
.disposed(by: disposeBag)
}
Copy the code
2. TextFiled input
func setupTextFiled() {/ / input change self. TextFiled. Rx. Text. OrEmpty. Changed. The subscribe (onNext: {(text)in
print(text)}). Prompt (by: disposeBag) // Text bound to button self.textfiled.rx.text.bind (to: self.button.rx.title()). disposeBag) }Copy the code
3.scrollView contentOffset
func setupScrollerView() {
scrollView.rx.contentOffset
.subscribe(onNext: { [weak self](content) inself? .view.backgroundColor = uicolor. init(red: content.y/255*0.8, green: content.y/255*0.6, blue: content.y/255*0.3, alpha: 1) }) .disposed(by: disposeBag) }Copy the code
4. Hand gestures
func setupGestureRecognizer() {let tap = UITapGestureRecognizer()
self.label.addGestureRecognizer(tap)
self.label.isUserInteractionEnabled = true
tap.rx.event
.subscribe(onNext: { (tap) in
print(tap)
})
.disposed(by: disposeBag)
}
Copy the code
5.timer
func setupTimer() {
timer = Observable.interval(1, scheduler: MainScheduler.instance)
timer.subscribe { (num) in
print(num)
}.disposed(by: disposeBag)
}
Copy the code
6.KVO
func setupKVO() {
self.person.rx.observeWeakly(String.self, "name")
.subscribe (onNext:{ (value) in
print(value ?? "err")
})
.disposed(by: disposeBag)
}
Copy the code
7. Inform
func setupNotification(){
NotificationCenter.default.rx.notification(UIResponder.keyboardWillShowNotification)
.subscribe { (notice) in
print(notice)
}
.disposed(by: disposeBag)
}
Copy the code
RxSwift advantage
- RxSwift makes code reusable and reduces the amount of code.
- RxSwift increases code readability because declarations are immutable.
- RxSwift makes it easier to understand business code, abstract asynchronous programming, and unify code styles.
- RxSwift makes it easier to write integration unit tests, increasing code stability.