RxSwift概念系列入门

2019-10-22 15:24:28 浏览数 (1)

基本核心概念 Observable

Observable的层级概念

public class Observable<Element> : ObservableType ---->

public protocol ObservableType: ObservableConvertibleType

ObservableType的核心作用

1 定义统一的方法

代码语言:javascript复制
 func subscribe<Observer: ObserverType>(_ observer: Observer) -> Disposable where Observer.Element == Element

2 使子类统一具有可观察功能

代码语言:javascript复制
extension ObservableType {
    
    /// Default implementation of converting `ObservableType` to `Observable`.
    public func asObservable() -> Observable<Element> {
        // temporary workaround
        //return Observable.create(subscribe: self.subscribe)
        return Observable.create { o in
            return self.subscribe(o)
        }
    }
}

常用使用

//Observable一系列方法

Observable.from(["1","2"]).subscribe{

print($0)

}.dispose()

Observable.of("1","2").subscribe{

print($0)

}.dispose()

Observable<String>.create { (observer) -> Disposable in

observer.onNext("1")

observer.onCompleted()

return Disposables.create()

}.subscribe{

print($0)

}.dispose()

Observable.range(start: 0, count: 10).subscribe{

print($0)

}

var times = 0

let factory = Observable<Any>.deferred {

times =1

return Observable.of(0..<times)

}

for i in 0...10{

factory.subscribe{

print($0)

}

}

订阅模式

//订阅

Observable.of("A","B").subscribe{

event in

print(event)

}

//可以缩写省略

Observable.of("A" ... "D").subscribe{

print($0)

}

订阅可以关注整个过程或者某过程某一部分

代码语言:javascript复制
//订阅显示整个过程
Observable.of("A","B","C").subscribe(onNext: { (item) in
    print(item)
}, onError: { (error) in
    print(error)
}, onCompleted: {
    
}) {
    
}

//关注某一个过程
Observable.of("A").subscribe(onNext: { (item) in
 print(item)
})

Variables的使用

代码语言:javascript复制
let disposeBag = DisposeBag()
   struct Person {
      var name: Variable<String> //再次修改的时候会重新发送single
   }
   let scott = Person(name: Variable("Scott"))
   let lori = Person(name: Variable("Lori"))
   let person = Variable(scott)
person.asObservable().flatMap { (p) -> Observable<String> in
    return p.name.asObservable()
}.subscribe(onNext: { (name) in
print(name)
    }).disposed(by: disposeBag)

    person.value = lori
    scott.name.value = "Eric"

通过Variable可以监听内部Value值修改变化,如上栗中 person.value = lori scott.name.value = "Eric"进行修改时均会一起注册监听的回调

更直观的例子

代码语言:javascript复制
let search = Variable("iOS")
search.asObservable().map{
    $0.lowercased()
    }.distinctUntilChanged()
    .subscribe { (e:Event<String>) in
    print(e)
}.disposed(by: disposeBag)

search.value = "IOS"
search.value = "Rx"

当修改search的value时订阅回调

0 人点赞