平常的写法
let image: UIImage = UIImage(named: ...)
imageView.image = image
绑定的写法
//可监听序列
let image: Observable<UIImage> = ...
//imageView.rx.image 观察者
image.bind(to: imageView.rx.image)
上面的同步机制就是 数据绑定
//这里是分开的写法
// Observable
let text = usernameOutlet.rx.text.orEmpty.asObservable()
// Observable
let passwordValid = text
// Operator
.map { $0.count >= minimalUsernameLength }
// Observer
let observer = passwordValidOutlet.rx.isHidden
// Disposable
let disposable = passwordValid
// Scheduler 用于控制任务在那个线程队列运行
.subscribeOn(MainScheduler.instance)
.observeOn(MainScheduler.instance)
.bind(to: observer)
...
// 取消绑定,你可以在退出页面时取消绑定
disposable.dispose()
typealias JSON = Any
let json: Observable<JSON> = Observable.create { (observer) -> Disposable in
let task = URLSession.shared.dataTask(with: ...) { data, _, error in
guard error == nil else {
observer.onError(error!)
return
}
guard let data = data,
let jsonObject = try? JSONSerialization.jsonObject(with: data, options: .mutableLeaves)
else {
observer.onError(DataError.cantParseJSON)
return
}
observer.onNext(jsonObject)
observer.onCompleted()
}
task.resume()
//Disposables.create { task.cancel() } 说明如果数据绑定被清除(订阅被取消)的话,就取消网络请求
return Disposables.create { task.cancel() }
}
public enum Event<Element> {
case next(Element)
case error(Swift.Error)
case completed
}
发出一个元素,或一个 error 事件
- 1
func getRepo(_ repo: String) -> Single<[String: Any]> {
return Single<[String: Any]>.create { single in
let url = URL(string: "https://api.github.com/repos/\(repo)")!
let task = URLSession.shared.dataTask(with: url) {
data, _, error in
if let error = error {
single(.error(error))
return
}
guard let data = data,
let json = try? JSONSerialization.jsonObject(with: data, options: .mutableLeaves),
let result = json as? [String: Any] else {
single(.error(DataError.cantParseJSON))
return
}
single(.success(result))
}
task.resume()
return Disposables.create { task.cancel() }
}
}
- Completable
- Maybe
共享附加作用
- Driver, 驱动UI
Driver会回放事件给新的观察者, 所以观察点击事件的响应的时候, 用 Driver就不合适了,用signal
- Signal 事件序列用singal
- ControlEvent, 专门用于描述UI控件所产生的事件