Skip to content

Instantly share code, notes, and snippets.

@KentarouKanno
Last active April 19, 2020 05:20
Show Gist options
  • Save KentarouKanno/a808d749d3c5d8ef0f5eee8c6a352eab to your computer and use it in GitHub Desktop.
Save KentarouKanno/a808d749d3c5d8ef0f5eee8c6a352eab to your computer and use it in GitHub Desktop.

Observalbe

let observable = Observable.of(
    "R",
    "Rx",
    "RxS",
    "RxSw",
    "RxSwi",
    "RxSwif",
    "RxSwift")

_ = observable
    .subscribe(onNext: {
        print($0)
    }, onCompleted: {
        print("終了")
    })
R
Rx
RxS
RxSw
RxSwi
RxSwif
RxSwift
終了

filterを適用

let observable = Observable.of(
    "R",
    "Rx",
    "RxS",
    "RxSw",
    "RxSwi",
    "RxSwif",
    "RxSwift")

_ = observable
    .filter { $0.count >= 2 }
    .subscribe(onNext: {
        print($0)
    }, onCompleted: {
        print("終了")
    })
Rx
RxS
RxSw
RxSwi
RxSwif
RxSwift
終了

filterとmapを適用

let observable = Observable.of(
    "R",
    "Rx",
    "RxS",
    "RxSw",
    "RxSwi",
    "RxSwif",
    "RxSwift")

_ = observable
    .filter { $0.count >= 2 }
    .map { $0.lowercased() }
    .subscribe(onNext: {
        print($0)
    }, onCompleted: {
        print("終了")
    })
rx
rxs
rxsw
rxswi
rxswif
rxswift
終了

map と subscribe

_ = Observable.just(10)
    .map { $0 * 2 }
    .subscribe(onNext: {
        print($0) // => 20
    })

map と subscribe (引数と戻り値を明示)

_ = Observable.just(10)
    .map { (arg: Int) -> Int in
        return arg * 2 }
    .subscribe(onNext: { (arg: Int) -> Void in
        print(arg) // => 20
    })

map で String に変換したものを subscribe

_ = Observable.just(10)
    .map { (arg: Int) -> String in
        return "value: \(arg)" }
    .subscribe(onNext: { (arg: String) -> Void in
        print(arg) // => ""value: 10""
    })

PublishSubjectによるイベントの発火

let subject = PublishSubject<String>()

subject
    .subscribe(onNext: {
        print("onNext: ", $0)
    })

subject.onNext("A")
subject.onNext("B")
subject.onNext("C")
subject.onNext("D")
subject.onCompleted()
onNext:  A
onNext:  B
onNext:  C
onNext:  D

dispose()メソッド呼び出しによりストリームを破棄する

let subject = PublishSubject<String>()

let subscription = subject
    .subscribe(onNext: {
        print("onNext: ", $0)
    }, onCompleted: {
        print("終了")
    }, onDisposed: {
        print("破棄")
    })

subject.onNext("1")
subject.onNext("2")
subscription.dispose()
subject.onNext("3")
subject.onNext("4")
subject.onCompleted()
onNext:  1
onNext:  2
破棄
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment