1. 程式人生 > >RxSwift基本使用(一)

RxSwift基本使用(一)

signal ret creat ont 條件 接收 參考 觀察 com

備註:本文參考自田騰飛博文 [RxSwift入坑解讀-你所需要知道的各種概念] (http://www.codertian.com/2016/11/27/RxSwift-ru-keng-ji-read-document/),出於個人學習以及筆記需要特記錄下RxSwift基本使用

概念

Observable : 可被觀察的,事件源

Observer : 觀察者,觀察者需要訂閱Observable,才能受到其發出的事件

DisposeBag : 相當於iOS中的ARC,會在適當的時候銷毀觀察者,自動去釋放資源

如果需要手動銷毀觀察者直接調用dispose()方法,例:
Observable.empty().subscribe { (str:Event) in
print(“empty:”,str)
}.dispose()

subscribe : 訂閱者,用於訂閱sequence發出的事件

基本使用

never

never就是創建一個sequence,但不發出任何事件信號

let bag = DisposeBag()
Observable.never().subscribe { (str :Event<String>) in
    print("never:",str) //無
}.addDisposableTo(bag)

備註:為了方便簡潔,後續例子中創建bag變量的代碼將省略

empty

empty創建一個空的sequence,但只能發出一個completed事件

Observable.empty().subscribe { (str :Event<String>) in
    print("empty:",str)
}.addDisposableTo(bag)

//empty: completed

just

just創建一個sequence,但只能發出一種特定的事件,能正常結束

Observable.just("just").subscribe { (str :Event<String>) in
    print("just:",str)
}.addDisposableTo(bag)

//just:next(just) 
//just:completed

of

創建一個sequence能發出很多種事件信號

Observable.of("1","2","3").subscribe { (str) in
    print("of:",str)
}.addDisposableTo(bag)

    /**
    of: next(1)
    of: next(2)
    of: next(3)
    of: completed
    */

   //subscribe onNext 直接取值

    Observable.of("1","2","3").subscribe(onNext: { (str) in
        print("of2:",str)
    }).addDisposableTo(bag)

    /**
     of2: 1
     of2: 2
     of2: 3
     */

from

from從集合中創建sequence,例如數組,字典或者Set

    Observable.from([10,100,1000]).subscribe(onNext: { (num) in
        print("from:",num)
    }).addDisposableTo(bag)

    /**
     from: 10
     from: 100
     from: 1000
     **/

create

create 自定義可觀察的sequence

    //create 自定義可觀察的sequence
    let myObservable = Observable.create { (observer:AnyObserver<Any>) -> Disposable in
        observer.onNext("12")
        observer.onNext("21")
        observer.onNext("123")
        observer.onCompleted()
        return Disposables.create()
    }
    myObservable.subscribe { (e:Event<Any>) in
        print("myObservable:",e)
        }.addDisposableTo(bag)

    /**
     myObservable: next(12)
     myObservable: next(21)
     myObservable: next(123)
     myObservable: completed
     **/

range

range 創建一個sequence,會發出這個範圍中所有事件

    Observable.range(start: 1, count: 5).subscribe(onNext: { (num) in
        print("range:",num)
    }).addDisposableTo(bag)
    /**
     range: 1
     range: 2
     range: 3
     range: 4
     range: 5
     **/

repeatElement

創建一個sequence,發出特定的事件n次

Observable.repeatElement("LouKit").take(3).subscribe { print($0)}.addDisposableTo(bag)


    //重復發出3次,如果沒有take 就無限次
    /**
     next(LouKit)
     next(LouKit)
     next(LouKit)
     completed
     **/

generate

generate是創建一個可觀察sequence,當初始化的條件為true的時候,他就會發出所對應的事件

    Observable.generate(initialState: 10, condition: {$0 < 15}, iterate: {$0 + 1}).subscribe(onNext: {print("generate",$0)}).addDisposableTo(bag)
    /**
     generate 10
     generate 11
     generate 12
     generate 13
     generate 14
     **/

deferred

deferred會為每一為訂閱者observer創建一個新的可觀察序列

    var index = 1
    let deferred = Observable<String>.deferred{

        print("index:",index)
        index += 1

        return Observable.create{ observer in
            observer.onNext("1")
            observer.onNext("2")
            observer.onCompleted()
            return Disposables.create()
        }
    }

    deferred.subscribe { print("調用1:",$0)}.addDisposableTo(bag)

    deferred.subscribe { print("調用2:",$0)}.addDisposableTo(bag)

    /**
     index: 1
     調用1: next(1)
     調用1: next(2)
     調用1: completed
     index: 2
     調用2: next(1)
     調用2: next(2)
     調用2: completed
     **/

do

主要用於在subscribe中onNext,onError,onCompleted前調用

    Observable.just("00").do(onNext: {print("doOnNext:",$0)},onError: {print("doOnError:",$0)},onCompleted: {print("doOnCompleted:")})
        .subscribe(onNext: { (str) in
            print("onNext:",str)
        }, onError: { (error) in
            print("onError")
        }, onCompleted: {
            print("onCompleted")
        }).addDisposableTo(bag)

    /**
     doOnNext: 00
     onNext: 00
     doOnCompleted:
     onCompleted
     **/

Subjects

Subjet是observable和Observer之間的橋梁,一個Subject既可以充當Obserable也可以充當Observer,即它可以發出事件,也可以監聽事件

PublishSubject

采用PublishSubject訂閱事件的時候,只能接收到訂閱他之後發生的事件

    let publicSubject = PublishSubject<String>()
    publicSubject.onNext("A")
    publicSubject.onNext("B")
    publicSubject.subscribe(onNext: {print("publicSubject:",$0)}) .addDisposableTo(bag)
    publicSubject.onNext("C")
    publicSubject.onNext("D")

    /**
     publicSubject: C
     publicSubject: D
     **/

ReplaySubject

可以接收到訂閱他之後以及之前發生的事件,對於要接受幾個以前的事件取決於bufferSize設置的大小

    let replaySubject = ReplaySubject<String>.create(bufferSize: 2)
    replaySubject.onNext("A")
    replaySubject.onNext("B")
    replaySubject.onNext("C")
    replaySubject.onNext("D")
    replaySubject.subscribe(onNext: {print("replaySubject:",$0)}) .addDisposableTo(bag)
    replaySubject.onNext("E")
    replaySubject.onNext("F")
    replaySubject.onNext("G")
    /**
     replaySubject: C
     replaySubject: D
     replaySubject: E
     replaySubject: F
     replaySubject: G
     **/

    //接受全部的事件
    let replaySubject2 = ReplaySubject<String>.createUnbounded()
    replaySubject2.onNext("A")
    replaySubject2.onNext("B")
    replaySubject2.subscribe(onNext: {print("replaySubject2:",$0)}) .addDisposableTo(bag)
    replaySubject2.onNext("E")
    replaySubject2.onNext("F")

    /**
     replaySubject2: A
     replaySubject2: B
     replaySubject2: E
     replaySubject2: F
     **/

BehaviorSubject

采用BehaviorSubject訂閱事件,會接收到訂閱之前的最後一個事件以及訂閱之後所有事件

    let behavior = BehaviorSubject(value: "behavior")
    behavior.onNext("A")
    behavior.onNext("B")
    behavior.subscribe(onNext: {print("behavior:",$0)}).addDisposableTo(bag)
    behavior.onNext("C")
    behavior.onNext("D")

    /**
     behavior: B
     behavior: C
     behavior: D
     **/

Variable

Variable是對BehaviorSubject一個包裝;

Variable當成Obserable, 讓訂閱者進行訂閱時, 需要asObserable轉成Obserable;

Variable發出事件, 直接修改對象的value即可;

當事件結束時,Variable會自動發出completed事件

    let variable = Variable("variable")

    variable.value = "A"
    variable.value = "B"
    variable.asObservable().subscribe { (event:Event<String>) in
        print("variable:",event)
        }.addDisposableTo(bag)
    variable.value = "C"
    variable.value = "D"

    /**
     variable: next(B)
     variable: next(C)
     variable: next(D)
     variable: completed
     **/

聯合操作

聯合操作就是把多個Observable流合成單個Observable流

startWith

在發出事件消息之前,先發出某個特定的事件消息。

    Observable.of(1,2).startWith(3).subscribe(onNext: {print($0)}).addDisposableTo(bag)

    /**
     3
     1
     2
     **/

merge

將多個Observable流合成單個Observable流,然後任何一個Observable發出事件都能被接收到

    let sub1 = PublishSubject<String>()
    let sub2 = PublishSubject<String>()

    Observable.of(sub1,sub2).merge().subscribe(onNext: { print($0) }).addDisposableTo(bag)
    sub1.onNext("sub1-1")
    sub1.onNext("sub1-2")

    sub2.onNext("sub2-1")
    sub1.onNext("sub1-2")
    sub2.onNext("sub2-2")
    /**
     sub1-1
     sub1-2
     sub2-1
     sub1-2
     sub2-2
     **/

zip

將多個Observable流合成單個Observable流,只有當多個Observable流同時發出事件時,並且把多個Observable流的內容合並成一個元組,才會觸發壓縮流的事件。

    let zip1 = PublishSubject<String>()
    let zip2 = PublishSubject<String>()

    Observable.zip(zip1,zip2){ zip1,zip2 in
        "\(zip1) \(zip2)"
        }.subscribe(onNext: { print($0) })
        .addDisposableTo(bag)

    zip1.onNext("zip1-1")
    zip1.onNext("zip1-2")
    zip2.onNext("zip2-1")
    zip2.onNext("zip2-2")

    /**
     zip1-1 zip2-1
     zip1-2 zip2-2
     **/

註意:merge、zip都能將多個Observable流合成單個Observable流,但合並後前者任何一個Observable發出事件都能被接收到,後者必須是多個流同時發出事件時才被接收到

combineLatest

將多個Observable流合並起來 並拿到其各個流的最新值,即每個合並的signal至少都有過一次onNext,才會觸發合並的流

    let ps1 = PublishSubject<String>()
    let ps2 = PublishSubject<String>()

    Observable.combineLatest(ps1, ps2) { element1, element2 in
        "\(element1) \(element2)"
        }
        .subscribe(onNext: { print($0) })
        .addDisposableTo(bag)

    ps1.onNext("ps1-01")
    ps1.onNext("ps1-02")
    ps2.onNext("ps2-01")

    /**
     ps1-02 ps2-01
     **/

switchLatest

用於對事件流進行轉換,即一個Observable中的內容還是Observable。(個人理解)

    let bs1 = BehaviorSubject(value: "1")
    let bs2 = BehaviorSubject(value: "A")

    let variable = Variable(bs1)
    variable.asObservable().switchLatest().subscribe(onNext: {print($0)}).addDisposableTo(bag)
    bs1.onNext("2")
    variable.value = bs2
    bs1.onNext("3")
    bs2.onNext("B")
    /**
     1
     2
     A
     B
     **/

RxSwift基本使用(一)