Getting started with RxSwift

以下資料參考自Ref,這裡僅作個人學習整理

  • Definition of ReactiveX
  • Advantage of ReactiveX
  • Definition of RxSwift
  • Example of RxSwift
  • 補充

Definition of ReactiveX:

  • An API for asynchronous programming with observable streams.
  • ReactiveX is a combination of the best ideas from the Observer pattern, the Iterator pattern, and functional programming.
  • ReactiveX是一組tool讓指令式程式設計(imperative programming)的程式語言能夠不用管資料是同步或非同步的狀況下去操作資料序列。它提供了一組sequence operators來操作在序列上的每個item。

用一句話說明Rx:

利用observer pattern和sequence operators,讓我們能夠用宣告式(declarative)的方式去處理同步或非同步的data or event stream。

Advantage of Rx:

  • Composable, Reusable (p.s. 訂閱者模式優點)
  • Understandable and concise (p.s. Declartive優點)
  • 避免Mutable state,讓資料流呈單向流動 (p.s. Function Reactive programming優點)
  • 方便處理非同步事件(p.s. Reactive programming的優點)

Definition of RxSwift

RxSwift is the Swift-specific implementation of the Reactive Extensions standard.

Note:

有人說Rx是Functional Reactive Programing(FRP),在官方介紹中有特別說明,這不是那麼正確,Rx可能會是Functional,可能會是Reactive,但FRP是另外一件東西,在定義的上 FRP 則是隨著時間continuously(連續的)操作數值,Rx則是 discrete(離散的)

Example of RxSwift

每0.5秒輸出一個累進數值,藉由subscribe,觸發到onNext這個closure,印出收到的數值

       let observable = Observable<Int>.interval(.milliseconds(500), scheduler: MainScheduler.instance)
        observable
            .subscribe(onNext: { element in
                print(element)
            }, onError: { error in
                print(error)
            }, onCompleted: {
                print("onCompleted")
            }, onDisposed: {
                print("onDisposed")
            })

補充:

  • Observer pattern(觀察者模式)
  • Iterator pattern(疊代器模式)
  • Imperative programming(指令式程式設計)
  • Declarative programming(宣告式程式設計)
  • Functional programming(函式語言程式設計)

Collections:

  • In Rx, you begin with a collection and end with a collection
  • Rx methods, also called operators, always return a new collection and never mutate the passed collection

Ref: https://www.slideshare.net/rockncoder/a-quick-intro-to-reactivex

待整理部分:

  • Observer pattern研究與分析
  • Iterator pattern研究與分析

Ref:

https://ithelp.ithome.com.tw/articles/10237162

https://www.slideshare.net/rockncoder/a-quick-intro-to-reactivex

https://github.com/ReactiveX/RxSwift