Observable 是在 Swift 中观察值的最简单方法

Observable 是在 Swift 中观察值的最简单方法。

如何

创建可观察和可变可观察

使用您可以创建和观察事件。
使用您可以观察事件,以避免对我们内部 API 的副作用。
MutableObservableObservable

class SomeViewModel {
    /// Public property, that can be read / observed by external classes (e.g. view controller), but not changed.
    var position: Observable<CGPoint> = {
        return positionSubject
    }
    // Or use the helper method Observable.asObservable()
    // lazy var position = positionSubject.asObservable()

    /// Private property, that can be changed / observed inside this view model.
    private let positionSubject = MutableObservable(CGPoint.zero)
}
迅速

使用自定义释放功能创建观察器

在某些情况下,可观察量在处于活动状态时需要资源,在处置时必须清理这些资源。要处理此类情况,您可以将可选块传递给可观察初始值设定项,以便在处置可观察量时执行。

url.startAccessingSecurityScopedResource()
let observable = Observable([URL]()) {
    url.stopAccessingSecurityScopedResource()
}
迅速

模型属性作为@MutableObservable

现在将绑定/映射的属性标记为可观察并导出公共可观察

//Private Observer
@MutableObservable var text: String = "Test"

//add observer

_text.observe { (newValue, oldValue) in
    print(newValue)
}.add(to: &disposable)
        
//Public Observer

var textObserve: ImmutableObservable<String> {
    return _text
}

迅速

Add an observer

position.observe { p in
    // handle new position
}
Swift

Add an observer and specify the DispatchQueue

position.observe(DispatchQueue.main) { p in
// handle new position
}
Swift

Change the value

position.wrappedValue = p
Swift

Stop observing new values

position.observe {
    // This will stop all observers added to `disposal`
    self.disposal.dispose()
}.add(to: &disposal)

Swift

Memory management

For a single observer you can store the returned to a variableDisposable

disposable = position.observe { p in

Swift

For multiple observers you can add the disposable to a variableDisposal

position.observe { }.add(to: &disposal)
Swift

And always weakify when referencing inside your observerselfself

position.observe { [weak self] position in
Swift

Installation

CocoaPods

Observable is available through CocoaPods. To install
it, simply add the following line to your Podfile:

pod 'Observable'
Ruby

Swift Package Manager

Observable is available through .
Swift Package Manager (SwiftPM) is a tool for automating the distribution of Swift code.
It is integrated into the swift compiler and from Xcode 11, SwiftPM got natively integrated with Xcode.
Swift Package Manager

dependencies: [
    .package(url: "https://github.com/roberthein/Observable", from: "VERSION")
]
Swift

Migrations

1.x.y to 2.0.0

  • Observable is now MutableObservable
  • ImmutableObservable is now Observable
  • Observable.asImmutableObservable() is now Observable.asObservable()
  • Observable.value is now Observable.wrappedValue

Suggestions or feedback?

Feel free to create a pull request, open an issue or find me on Twitter.

GitHub

https://github.com/roberthein/Observable