RxSwift练习:https://github.com/flywo/RxSwiftPractice
关于RxSwift是什么,网上有很多文章,不详细讲解了,直接上代码。
创建只有单个元素的队列
let ob = Observable.just(one)
创建多个元素队列
let one = 1
let two = 2
let observable = Observable.of(one, two)
订购队列发出的事件
observable.subscribe({ (event) in
print("事件:", event)
})
从事件中获得元素
observable.subscribe({ (event) in
//event具有属性element,并且只有.next事件有该属性
if let element = event.element {
print("事件元素:", element)
}
})
订购事件,并处理.next方法
observable.subscribe(onNext: { (element) in
print("直接处理.next方法:", element)
})
创建空队列
//空队列必须声明一个特殊的类型
let observable = Observable<Void>.empty()
observable.subscribe(
onNext: { (element) in
//不会输出元素
print("空队列:\(element)")
},
onCompleted: {
print("空队列结束")
})
创建永久队列
let observable = Observable<Any>.never()
observable.subscribe(
//不会打印任何东西
onNext: { (element) in
print("永久队列:\(element)")
},
onCompleted: {
print("永久队列结束")
})
创建range队列
let observable = Observable.range(start: 1, count: 10)
observable.subscribe(onNext: { (element) in
print(element)
})
取消订阅
let observable = Observable.of("a", "b", "c")
//获得订购对象
let subscription = observable.subscribe({ (event) in
print(event)
})
//使用dispose()来取消订购,一旦订购被取消,队列则会停止发送事件
subscription.dispose()
使用管理者来管理订阅对象
let disposeBag = DisposeBag()
Observable.of("a", "c").subscribe {
print($0)
}.disposed(by: disposeBag)
自定义队列
//自定义错误
enum MyError: Error {
case anError
}
let disposeBag = DisposeBag()
//只有一个参数,subscribe。提供但被订购后的实现。
Observable<String>.create({ (observer) -> Disposable in
observer.onNext("1")
//同样会提前终止
// observer.onError(MyError.anError)
// observer.onCompleted()
//不会打印后面,因为completed提前结束了
observer.onNext("?")
return Disposables.create()
}).subscribe(
onNext: {print($0)},
onError: {print($0)},
onCompleted: {print("结束")},
onDisposed: {print("取消")})
//如果没有添加到bag中,则会造成内存泄露,永远不会结束和取消
.disposed(by: disposeBag)
队列工厂
let disposeBag = DisposeBag()
var flip = false
//deferred推迟创建
let factory: Observable<Int> = Observable.deferred{
flip = !flip
print("创建队列")
if flip {
return Observable.of(1, 2, 3)
}else {
return Observable.of(4, 5, 6)
}
}
for _ in 0...3 {
factory.subscribe{print($0, terminator:"")}.disposed(by: disposeBag)
print()
}
使用特性
let disposeBag = DisposeBag()
enum FileReadError: Error {
case fileNotFound, unreadable, encodingFailed
}
func loadText(from name: String) -> Single<String> {
return Single.create {single in
let disposable = Disposables.create()
guard let path = Bundle.main.path(forResource: name, ofType: "txt") else {
single(.error(FileReadError.fileNotFound))
return disposable
}
guard let data = FileManager.default.contents(atPath: path) else {
single(.error(FileReadError.unreadable))
return disposable
}
guard let contents = String(data: data, encoding: .utf8) else {
single(.error(FileReadError.encodingFailed))
return disposable
}
single(.success(contents))
return disposable
}
}
loadText(from: "ccc").subscribe {
switch $0 {
case .success(let string):
print(string)
case .error(let error):
print(error)
}
}.disposed(by: disposeBag)