Chapter 1: Hello RxSwift

2018-04-19  本文已影响69人  清無

RxSwift is a library for composing asynchronous and event-based code by using observable sequences and functional style operators, allowing for parameterized execution via schedulers.

RxSwift, in its essence, simplifies developing asynchronous programs by allowing your code to react to new data and process it in sequential, isolated manner.

Introduction to asynchronous programming

Cocoa and UIKit Asynchronous APIs

Asynchronous programming glossary(术语表)

RxSwift combines some of the best aspects of imperative code and functional code.

Foundation of RxSwift

A team at Microsoft worked on a library, independently from the core teams in the company, and sometime around 2009, offered a new client and server side framework called Reactive Extensions for .NET (Rx).

It was an installable add-on for .NET 3.5, and later became a built-in core library in .NET 4.0. It’s been an open source component since 2012.

Open sourcing the code permitted other languages and platforms to reimplement the same functionality, which turned Rx into a cross-platform standard.

RxSwift finds the sweet spot between traditionally imperative Cocoa code and purist functional code. It allows you to react to events by using immutable code definitions to process asynchronously pieces of input in a deterministic, composable way.

The three building blocks of Rx code are observables, operators, and schedulers.

Observables

class Observable

public class Observable<Element> : ObservableType{
}

protocol ObservableType

// 基础方法subscribe
public protocol ObservableType : ObservableConvertibleType{
    func subscribe<O: ObserverType>(_ observer: O) -> Disposable where O.E == E
}

// 基础扩展方法`asObservable()`
extension ObservableType {
    public func asObservable() -> Observable<E> {
    }
}

一个Obvervable对象只能抛出3个事件:

• A next event: 发生该订阅事件时抛出,携带最新的数据
• A completed event: 成功完成了该订阅事件是抛出
• An error event: 错误发生时会抛出

Operators

ObservableTypeObservable类包含了大量异步功能的离散的抽象方法 ,我们可以任意组合这些方法来实现更复杂的逻辑,将这些高度独立和可组合化的方法块,称之为Rx的Operators。

例如:实时监听设备方向,然后执行filter、map等Operators,然后subscribe给onNext响应,完成整个事件序列。

UIDevice.rx.orientation
  .filter { value in
    return value != .landscape
  }
.map { _ in
    return "Portrait is the best!"
  }
  .subscribe(onNext: { string in
    showAlert(text: string)
  })
事件响应链
Schedulers

Schedulers相当于简化版的GCD,是Rx对GCD的简化封装,更易于链式调用和使用。

subscription订阅和scheduler关系图

App architecture

RxSwift与MVVM

RxCocoa

例如UISwitch:

toggleSwitch.rx.isOn
  .subscribe(onNext: { enabled in
    print( enabled ? "it's ON" : "it's OFF" )
  })

Installing RxSwift

这一章节到这里就结束了,原作出自Raywenderlich

《Chapter 2: Observables》

如果对你有帮助,别忘了点个赞和关注~

上一篇 下一篇

猜你喜欢

热点阅读