Help us understand the problem. What is going on with this article?

RxSwift Observable生成関数まとめ

More than 3 years have passed since last update.

RxSwift Observable生成関数まとめ

はじめに

RxSwiftを触り始めて、ようやくReactive ExtensionsのObservable/Observer/Subscribe周りの関係性が分かってきたところで自分の勉強も兼ねてObservableの生成関数をまとめてみました。
Rx公式ページのCreating Observablesを元にしています。(リンクはこちら)

前提

Creating Observables

create


関数からObservableを生成します

create.png

Declaration

func create<E>(subscribe: (ObserverOf<E>) -> Disposable) -> Observable<E>

Sample Code

let source: Observable<Int> = create { (observer: ObserverOf<Int>) in
    sendNext(observer, 42)
    sendCompleted(observer)
    return AnonymousDisposable {
        print("disposed")
    }
}

let subscription = source.subscribe { (event: Event<Int>) -> Void in
    switch event {
    case .Next(let element):
        print("Next: \(element)")
    case .Completed:
        print("Completed")
    case .Error(let error):
        print("Error: \(error)")
    }
}

Log

Next: 42
Completed

defer


SubscribeするまではObservableを生成せずに、SubscribeされたタイミングでObservableを返すObservableを生成します

RxSwiftではdeferredという名前の関数がdeferの代わりに定義されています、Swift2.0からdefer構文が追加されたためと推測

defer.c.png

Declaration

func deferred<E>(observableFactory: () throws -> Observable<E>)

Sample Code

let source: Observable<Int> = deferred {
    return just(42)
}

let subscription = source.subscribe { (event: Event<Int>) -> Void in
    switch event {
    case .Next(let element):
        print("Next: \(element)")
    case .Completed:
        print("Completed")
    case .Error(let error):
        print("Error: \(error)")
    }
}

Log

Next: 42
Completed

empty


何も値を持たず、正常に終了するObservableを生成します

empty.c.png

Declaration

func empty<E>() -> Observable<E>

Sample Code

let source: Observable<Int> = empty()

let subscription = source.subscribe { (event: Event<Int>) -> Void in
    switch event {
    case .Next(let element):
        print("Next: \(element)")
    case .Completed:
        print("Completed")
    case .Error(let error):
        print("Error: \(error)")
    }
}

Log

Completed

never


何も値を持たず、終了しないObservableを生成します

never.c.png

Declaration

func never<E>() -> Observable<E>

Sample Code

let source: Observable<Int> = never()

let subscription = source.subscribe { (event: Event<Int>) -> Void in
    switch event {
    case .Next(let element):
        print("Next: \(element)")
    case .Completed:
        print("Completed")
    case .Error(let error):
        print("Error: \(error)")
    }
}

Log

throw


何も値を持たず、異常終了するObservableを生成します

RxSwiftではfailWithという名前の関数がthrowの代わりに定義されています

throw.c.png

Declaration

func failWith<E>(error: ErrorType) -> Observable<E>

Sample Code

let error = NSError(domain: "com.rxswiftsample.throw", code: -1, userInfo: nil)
let source: Observable<Int> = failWith(error)

let subscription = source.subscribe { (event: Event<Int>) -> Void in
    switch event {
    case .Next(let element):
        print("Next: \(element)")
    case .Completed:
        print("Completed")
    case .Error(let error):
        print("Error: \(error)")
    }
}

Log

Error: Error Domain=rxswiftsample.throw Code=-1 "(null)

from


ある値の配列をObservableに変換します

from.c.png

Declaration

func from<E, S where S: SequenceType, S.Generator.Element == E>(sequence: S) -> Observable<E>

Sample Code

let source: Observable<Int> = from([1, 2, 3])

let subscription = source.subscribe { (event: Event<Int>) -> Void in
    switch event {
    case .Next(let element):
        print("Next: \(element)")
    case .Completed:
        print("Completed")
    case .Error(let error):
        print("Error: \(error)")
    }
}

Log

Next: 1
Next: 2
Next: 3
Completed

just


ある特定の値をを元にObservableを生成します

just.c.png

Declaration

func just<E>(value: E) -> Observable<E>

Sample Code

let source: Observable<Int> = just(42)

let subscription = source.subscribe { (event: Event<Int>) -> Void in
    switch event {
    case .Next(let element):
        print("Next: \(element)")
    case .Completed:
        print("Completed")
    case .Error(let error):
        print("Error: \(error)")
    }
}

Log

Next: 42
Completed

range


特定の範囲の整数を元にObservableを生成します

RxSwiftにはrange関数は用意されてなかったのでfrom関数を例にしています、恐らくですがSwiftには言語機能として範囲演算子があるので用意されなかったと推測。

range.c.png

Declaration

func from<E, S where S: SequenceType, S.Generator.Element == E>(sequence: S) -> Observable<E>

Sample Code

let source: Observable<Int> = from(0..<3)

let subscription = source.subscribe { (event: Event<Int>) -> Void in
    switch event {
    case .Next(let element):
        print("Next: \(element)")
    case .Completed:
        print("Completed")
    case .Error(let error):
        print("Error: \(error)")
    }
}

Log

Next: 1
Next: 2
Next: 3
Completed
Why do not you register as a user and use Qiita more conveniently?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away