因为学过RAC,swift所以只记录自己感兴趣的部分内容。网上有系列文章写得很好RxSwift 使用详解系列也很详细。
pod集成
运用时swift项目一般pod添加如下两个
pod.png
创建 Observable 序列
在RxSwift_V1.1英文文档中的创建方法描述中有几个方法
empty()方法
empty.png创建一个空内容的观察序列,只执行
.completed event
func testEmpty() {
let observable = Observable<Void>.empty()
observable.subscribe(onNext: { (result) in
print("======\(result)")
}, onError: { (err) in
print("======\(err)")
}, onCompleted: {
print("=======Completed")
})
}
只打印了completed
never() 方法
该方法创建一个永远不会发出 Event(也不会终止)的 Observable 序列,原文的解释:
As opposed to the empty operator, the never operator creates an observable that doesn’t emit anything and never terminates. It can be use to represent an infinite duration. Add this example to the playground:
可观察序列的处理与终止
在原文中:Remember that an observable doesn’t do anything until it receives a subscription. It’s the subscription that triggers an observable to begin emitting events, up until it emits an .error or .completed event and is terminated. You can manually cause an observable to terminate by canceling a subscription to it.
原意大概是这样的,事件发生了错误,或已完成才使观察结束,可以人为的取消它。
dispose()
取消订阅,调用dispose ()。所以在我们使用时一般要写subscription.dispose()
,但每写一个订阅就写一个.dispose()
很麻烦所以才有了disposed(by: disposeBag)
的设计,对信号进行自动管理。
Managing each subscription individually would be tedious, so RxSwift includes a DisposeBag type. A dispose bag holds disposables — typically added using the .disposed(by:) method — and will call dispose() on each one when the dispose bag
在英文文档中有一句话很重要:Why bother with disposables at all? If you forget to add a subscription to a dispose bag, or manually call dispose on it when you’re done with the subscription, or in some other way cause the observable to terminate at some point, you will probably leak memory. Don’t worry if you forget; the Swift compiler should warn you about unused disposables.
(如果你忘记添加dispose bag,或手动调用dispose,这会引起内存泄露,但swift编译器会提示你)
文档中一个有意思的程序,可以运行体验。
func testObservd() {
let disposeBag = DisposeBag()
Observable<String>.create { observer in
// 1
observer.onNext("1")
// observer.onError(NSError.init(domain: "yydomain", code: -1, userInfo: nil))
// 2
// observer.onCompleted()
// 3
observer.onNext("?")
// 4
return Disposables.create()
}
.subscribe(
onNext: { print($0) },
onError: { print($0) },
onCompleted: { print("Completed") },
onDisposed: { print("Disposed") }
)
.disposed(by: disposeBag)
}
- 如果不写
observer.onCompleted和disposeBag
会导致内存泄露。- 不写
observer.onCompleted
写了disposeBag信号会正常结束,不会泄露。- 用
observer.onError, observer.onCompleted和 disposed(by: disposeBag)
都能正常的结束。
总结
- 记录了部分 observer 的创建,取消,终止。
- 建议还是读RxSwift英文文档,那样感受才深。
网友评论