はじめに
某企画でメンターをすることになり、
RxSwiftについて何から教えようかと考えたときに、
公式レポジトリのイントロのコンテンツが良さそうだと思い書き残しています。
背景として以下2点を説明済みなので、0から読むには少しだけ違和感があるかもしれません。
- RxSwiftとは何か
- 宣言型と命令型の違い
Why use RxSwift?
A vast majority of the code we write involves responding to external events. When a user manipulates a control, we need to write an @IBAction handler to respond. We need to observe notifications to detect when the keyboard changes position. We must provide closures to execute when URL sessions respond with data. And we use KVO to detect changes to variables. All of these various systems makes our code needlessly complex. Wouldn't it be better if there was one consistent system that handled all of our call/response code? Rx is such a system.
イベントの応答に対してIBActionや通知の監視、クロージャ、KVOなどさまざまな手段が存在し、
これらの様々なシステムが、コードを不必要に複雑にさせます。
「全てのコール/レスポンスを一貫した1つのシステムで制御できたら良いよね、
Rxはそういうものだ」と言っています。
個人的な意見としてはSwiftのDelegateを絶対に使わないようにする、
となると逆に実装がしづらいので、一部のUIオブジェクトに関してはSwiftのDelegateをしようする場面もあります。
Every Observable instance is just a sequence.
The key advantage for an Observable sequence vs. Swift's Sequence is that it can also receive elements asynchronously. This is the essence of RxSwift. Everything else expands upon this concept.
ObservableシーケンスとSwiftのシーケンスの主な利点は、
要素を非同期的に受け取ることができることで、これこそがRxSwiftの本質です。
他の全てはこの概念を拡張しています。
・An Observable (ObservableType) is equivalent to a Sequence.
Observableはシーケンスと同等である
・The ObservableType.subscribe(_:) method is equivalent to Sequence.makeIterator().
ObservableType.subscribeメソッドはSequence.makeIterator()と同等である
・ObservableType.subscribe(_:) takes an observer (ObserverType) parameter, which will be subscribed to automatically receive sequence events and elements emitted by the Observable, instead of manually calling next() on the returned generator.
subscribeメソッドはobserverのパラメータを受け取り、
nextメソッドで手動で呼び出す代わりにObservableによって発行されたイベント(next, errorなど)と要素を自動で受け取ります。
observableから発行されたイベントはsubscribeすると受け取れる
ということ
// disposeや実際にイベントを流しているjustメソッドは置いておいて、
// 発行されたイベントをsubscribeで購読し、受け取っていることを理解してもらえればok
let disposeBag = DisposeBag()
Observable.just("element")
.subscribe({onNext: { string in
print(string) // element
}).disposed(by: disposeBag)
If an Observable emits a next event (Event.next(Element)), it can continue to emit more events. However, if the Observable emits either an error event (Event.error(ErrorType)) or a completed event (Event.completed), the Observable sequence cannot emit additional events to the subscriber.
Observableがnextイベントを発行する場合、続けてイベントを発行することができるが、
errorまたはcompletedイベントを流した場合は追加のイベントを発行することができない。
※イベントは 要素を正常に流すnextや、異常を伝えるerror、イベントの終了を伝えるcompletedがある。
Observables and observers (aka subscribers)
Observables will not execute their subscription closure unless there is a subscriber. In the following example, the closure of the Observable will never be executed, because there are no subscribers:
Observableは、subscriberが存在しないかぎりサブスクリプションクロージャを実行しません。
次の例ではsubscriberがいないためにクロージャが実行されないものです。
※正確には購読されなくてもイベントを発行するHotなObservableと、今回のような購読されないとイベントを発行しないColdなObservableがあります。ほとんどのObservableはColdです。後々理解していけばokです。
example("Observable with no subscribers") {
_ = Observable<String>.create { observerOfString -> Disposable in
print("This will never be printed") // 呼ばれない
observerOfString.on(.next("😬"))
observerOfString.on(.completed)
return Disposables.create()
}
}
次の例ではsubscriberがいるためクロージャが実行されるものです。
example("Observable with subscriber") {
_ = Observable<String>.create { observerOfString in // createでObserverを作っている
print("Observable created") // 呼ばれる
observerOfString.on(.next("😉"))
observerOfString.on(.completed)
return Disposables.create()
}
.subscribe { event in
print(event) // 😉
}
}
以上です。
より学びたい場合は ドキュメントを参照してください。