Swift -- 响应式编程

2022-02-09  本文已影响0人  冰棍儿好烫嘴

响应式编程(Reactive Programming,简称RP)

RxSwift

1.Podfile
use_frameworks!
target 'target_name' do
    pod 'RxSwift', '~> 5' 
    pod 'RxCocoa', '~> 5'
end
2.命令行
`pod repo update`
`pod install`
3.导入模块
import RxSwift
import RxCocoa

RxSwift的核心角色

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
}
创建、订阅Observable1
创建:
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
    switch event{
        case .next(let element):
            print("next",element)
        case .error(let error):
            print("error",error)
        case .completed:
            print("completed")
    }
}
或者:
observable.subscribe(onNext: { element in
    print("next", element)
}, onError: {error in
  print("error", error)
}, onCompleted: {
  print("completed")
})
创建、订阅Observable2
let observable = Observable<Int>.timer(.seconds(2),period:.seconds(1),scheduler:MainScheduler.instance)
2秒后每隔一秒钟在主线程发送一次事件
绑定到label上去:
observable.map{"数值是:\($0)"}.bind(to:label.rx.text)
Disposable
let disposable = observable.subscribe { event in
    switch event{
        case .next(let element):
            print("next",element)
        case .error(let error):
            print("error",error)
        case .completed:
            print("completed")
    }
}
disposable.dispose()
observable.subscribe { event in
    switch event{
        case .next(let element):
            print("next",element)
        case .error(let error):
            print("error",error)
        case .completed:
            print("completed")
    }
}.dispose()
只订阅一次,订阅完就取消了
1、立即取消订阅(一次性订阅)
observable.subscribe { event in
    print(event)
}.dispose()
2、当bag销毁(deinit)时,会自动调用Disposable实例的dispose(回收袋,自动释放池的感觉)
let bag = DisposeBag()
observable.subscribe { event in
    print(event)
}.disposed(by:bag)
3、self销毁(deinit)时,会自动调用Disposable实例的dispose
let _ = observable.takeUntil(self.rx.deallocated).subscribe{ event in
    print(event)
}
observable.subscribe(onNext: { element in
    print("next", element)
}, onError: {error in
  print("error", error)
}, onCompleted: {
  print("completed")
},onDisposed:{
  print("disposed")//dispose时的回调
}).dispose()

创建Observer

1、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()

2、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()

实例

button每隔一秒隐藏一次

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)
上一篇 下一篇

猜你喜欢

热点阅读