RxSwift Observable生成関数まとめ

# RxSwift Observable生成関数まとめ

## はじめに

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

## 前提

* Swift2.0
* Xcode7.0 beta 6
* [RxSwift branch: origin/rxswift-2.0](https://github.com/ReactiveX/RxSwift/tree/rxswift-2.0)

## Creating Observables

### **create**

----

**関数からObservableを生成します**

![create.png](https://qiita-image-store.s3.amazonaws.com/0/46751/0d9d8893-50c5-2e14-d084-c80a1cef6a7a.png)

#### Declaration

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

#### Sample Code

```swift
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](https://qiita-image-store.s3.amazonaws.com/0/46751/71ebf65b-b360-01f8-b944-deaf6c0141ba.png)

#### Declaration

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

#### Sample Code

```swift
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](https://qiita-image-store.s3.amazonaws.com/0/46751/91040bef-91d5-2e9f-1fef-df83faf265c8.png)

#### Declaration

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

#### Sample Code

```swift
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](https://qiita-image-store.s3.amazonaws.com/0/46751/c6860992-b422-e315-87c4-ab2a33398ea1.png)

#### Declaration

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

#### Sample Code

```swift
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](https://qiita-image-store.s3.amazonaws.com/0/46751/b78db854-c0c7-ca8a-a891-a2b3563a9519.png)

#### Declaration

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

#### Sample Code

```swift
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](https://qiita-image-store.s3.amazonaws.com/0/46751/f087b21f-c305-aff6-72b4-610451b08217.png)

#### Declaration

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

#### Sample Code

```swift
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](https://qiita-image-store.s3.amazonaws.com/0/46751/033cd12a-0269-2f5c-5ddd-19e2a6163c87.png)

#### Declaration

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

#### Sample Code

```swift
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関数](http://qiita.com/__moai/items/de94c574b25ea4f0ef17#from)を例にしています、恐らくですがSwiftには言語機能として範囲演算子があるので用意されなかったと推測。

![range.c.png](https://qiita-image-store.s3.amazonaws.com/0/46751/c9ebe204-2d20-c69d-9635-54a2f8c68510.png)

#### Declaration

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

#### Sample Code

```swift
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
```