Observator
Observator 是一个简单的 Swift 全局数据共享机制。一个用于在特定类型周围创建泛型单例包装器的类依赖项,具有内置通知。这种设置允许你在应用的各个组件中异步读取和写入数据。
示例
基本用法
// Define your custom observator subclass:
class CityName: Observator<String> {}
// Listen for data modification:
CityName.shared.subscribe(self, selector: #selector(cityNameChanged))
// Update the stored value:
CityName.shared.data = "Helsinki"
高级功能
// You can override some methods in the observator subclass to automatically transform the stored data
class CityName: Observator<String> {
override func readTransform(_ input: String) -> String {
return "\(input) Finland"
}
}
// Which should return on access: "Helsinki Finland"
CityName.shared.data = "Helsinki"
// It also supports subclasses of a customized observator
class DepartureCity: CityName {}
class DestinationCity: CityName {}
// Should be: "Tampere Finland"
DepartureCity.shared.data = "Tampere"
// Should be: "Oulu Finland"
DestinationCity.shared.data = "Oulu"
// Observator can be also used to store the data fetching and processing logic of custom types. You can create a generic subclass with the shared data management features and do the fetching in specialized subclasses.
class APIObservator<T>: Observator<T> {
let session = URLSession(configuration: .default)
let baseURL = URL(string: "...")!
}
class CustomerList: APIObservator<[Customer]> {
func fetchCustomers() {
session.dataTask(with: baseURL) { (data, _, _) in
if let data = data {
self.data = try? JSONDecoder().decode([Customer].self, from: data)
}
}
}
}
安装
手动:只需将 Observator.swift
拷贝到你的项目中。
CocoaPods:Observator 通过 CocoaPods 提供。要安装它,只需将以下行添加到你的 Podfile 中
pod 'Observator'