Swift响应式编程-RxSwift简单入门

2021-07-14  本文已影响0人  Amok校长

1、背景

    响应式编程(Reactive Programming,简称RP)也是一种编程范式,于1997年提出,可以简化异步编程,提供更优雅的数据绑定
  一般与函数式融合在一起,所以也会叫做:函数响应式编程(Functional Reactive Programming,简称FRP)

比较著名的、成熟的响应式框架  
  ReactiveCocoa
  简称RAC,有Objective-C、Swift版本
  官网: http://reactivecocoa.io/
  github:https://github.com/ReactiveCocoa

  ReactiveX(推荐)
  简称Rx,有众多编程语言的版本,比如RxJava、RxKotlin、RxJS、RxCpp、RxPHP、RxGo、RxSwift等等
  官网: http://reactivex.io/
  github: https://github.com/ReactiveX

2、RxSwift安装

RxSwift(ReactiveX for Swift),ReactiveX的Swift版本
  源码:https://github.com/ReactiveX/RxSwift
  中文文档: https://beeth0ven.github.io/RxSwift-Chinese-Documentation/

RxSwift的github上已经有详细的安装教程,这里只演示CocoaPods方式的安装
  Podfile
    use_frameworks!

    target 'target_name' do 
      pod 'RxSwift', '~> 5' 
      pod 'RxCocoa', '~> 5' 
    end

  命令行
    pod repo update
    pod install

  导入模块
    import RxSwift 
    import RxCocoa

模块说明
  RxSwift:Rx标准API的Swift实现,不包括任何iOS相关的内容
  RxCocoa:基于RxSwift,给iOS UI控件扩展了很多Rx特性

3、RxSwift的核心角色

Observable:负责发送事件(Event)
Observer:负责订阅Observable,监听Observable发送的事件(Event)

Event有3种
  next:携带具体数据
  error:携带错误信息,表明Observable终止,不会再发出事件
  completed:表明Observable终止,不会再发出事件

  public enum Event<Element> {
    /// Next element is produced. 
    case next(Element)

    /// Sequence terminated with an error. 
    case error(Swift.Error)

    /// Sequence completed successfully. 
    case completed
  }

4、Disposable

每当Observable被订阅时,都会返回一个Disposable实例,当调用Disposable的dispose,就相当于取消订阅
    在不需要再接收事件时,建议取消订阅,释放资源。有3种常见方式取消订阅
      1. 立即取消订阅(一次性订阅)
        observable.subscribe { event in 
          print(event) 
        }.dispose()
      2. 当bag销毁(deinit)时,会自动调用Disposable实例的dispose
        observable.subscribe { event in 
          print(event) 
        }.disposed(by: bag)
      3. self销毁时(deinit)时,会自动调用Disposable实例的dispose
        let _ = observable.take(until: self.rx.deallocated).subscribe { event in
          print(event) 
        }

5、创建、订阅Observable

/// 1.普通创建
var observable = Observable<Int>.create { observer in 
  observer.onNext(1) 
  observer.onCompleted() 
  return Disposables.create() 
} 
// 等价于 
observable = Observable.just(1) //只能发送单个数据
observable = Observable.of(1) //可发送多个数据
observable = Observable.from([1])//可发送多个数据

var observable = Observable<Int>.create { observer in 
  observer.onNext(1) 
  observer.onNext(2) 
  observer.onNext(3) 
  observer.onCompleted() 
  return Disposables.create() 
} 
// 等价于 
observable = Observable.of(1, 2, 3) 
observable = Observable.from([1, 2, 3])

observable.subscribe { event in 
  print(event) 
}.dispose()

observable.subscribe(onNext: { 
  print("next", $0) 
}, onError: {
  print("error", $0) 
}, onCompleted: {
  print("completed") 
}, onDisposed: {
  print("dispose") 
}).dispose()
//等价于
let bag = DisposeBag()
observable.subscribe { event in
    switch event {
    case .next(let element):
        print("next", element)
    case .error(let error):
        print("error",error)
    case .completed:
        print("completed")
    }
}.disposed(by: bag)

/// 2.间隔时间发送, 比如: 两秒之后, 每隔一秒钟在主线程发送一次
let observable = Observable<Int>.timer(.seconds(2), period: .seconds(1), scheduler: MainScheduler.instance)
//bind(to: 也是订阅, 传入参数为observer
let _ = observable
    .take(until: self.rx.deallocated)
    .map {"\($0)"}
    .bind(to: UILabel().rx.text)//rx.text 是一个observer

6、 创建Observer

//方式一: 通过AnyObserver
let observer = AnyObserver<Int>.init{ event in
    switch event {
    case .next(let data):
        print(data)
    case .completed:
        print("completed")
    case .error(let error):
        print("error", error)
    }
}
Observable.just(1).subscribe(observer).dispose()

//方式二: 通过Binder
let binder = Binder<String>(label){ label, text in
    label.text = text
}
Observable.just(1).map{"数值是\($0)"}.subscribe(binder).dispose()
Observable.just(1).map{"数值是\($0)"}.bind(to: binder).dispose()

7、扩展Binder属性

/// 需求: 从两秒后开始, 按钮每隔1秒进行一次显隐切换
//方法一:
let observable = Observable<Int>.timer(.seconds(2), period: .seconds(1), scheduler: MainScheduler.instance)
let binder = Binder<Bool>(button){ button, value in
    button.isHidden = value
}
observable.map{ $0 % 2 == 0 }.bind(to: binder).disposed(by: bag)

//方法二:
let observable = Observable<Int>.timer(.seconds(2), period: .seconds(1), scheduler: MainScheduler.instance)
observable.map{ $0 % 2 == 0 }.bind(to: button.rx.hidden).disposed(by: bag) //要实现button.rx.hidden, 需要给button扩展属性

//扩展Binder属性:  来实现button.rx.hidden
extension Reactive where Base: UIView{
    var hidden: Binder<Bool>{//只读计算属性
        Binder<Bool>(base) { view, value in
            view.isHidden = value
        }
    }
}

8、RxSwift的状态监听

/// ①监听按钮点击状态
button.rx.tap.subscribe(onNext: { 
  print("按钮被点击了1") 
}).disposed(by: bag)

/// ②监听列表状态
let data = Observable.just([ 
  Person(name: "Jack", age: 10), 
  Person(name: "Rose", age: 20) 
]) 
// 1.将数据绑定到TableView上
data.bind(to: tableView.rx.items(cellIdentifier: "cell")) { row, person, cell in
  cell.textLabel?.text = person.name
  cell.detailTextLabel?.text = "\(person.age)" 
}.disposed(by: bag)
// 2.TableViewCell点击事件响应
tableView.rx.modelSelected(Person.self) 
  .subscribe(onNext: { person in 
    print("点击了", person.name) 
  }).disposed(by: bag)

/// ③监听对象属性变化(类似KVO)
class Dog: NSObject { 
  //@objc dynamic应用于变量是为了让变量能够使用kvo机制
  @objc dynamic var name: String? 
} 

let dog = Dog()
let bag = DisposeBag()
dog.rx.observe(String.self, "name")
  .subscribe(onNext: { name in
    print("name is", name ?? "nil")
  }).disposed(by: bag)
dog.name = "Kris"
dog.name = "Amok"


/// ④监听通知
NotificationCenter.default.rx
      .notification(UIApplication.didEnterBackgroundNotification) 
      .subscribe(onNext: { notification in 
        print("APP进入后台", notification) 
      }).disposed(by: bag)

9、既是Observable,又是Observer

Observable.just(0.8).bind(to: slider.rx.value).dispose()

slider.rx.value.map { 
  "当前数值是:\($0)" 
}.bind(to: textField.rx.text).disposed(by: bag)

textField.rx.text
  .subscribe(onNext: { text in 
    print("text is", text ?? "nil") 
  }).disposed(by: bag)

// 总结: 诸如UISlider.rx.value、UTextField.rx.text这类属性值,既是Observable,又是Observer
//  它们是RxCocoa.ControlProperty类型
上一篇下一篇

猜你喜欢

热点阅读