RxSwift文档翻译1-Creating and Subscr
近期学习RxSwift查看过简书的一篇文章,是记录其学习过程,但是由于是在2015年左右记录的,和现在的版本有一定的出入,所以我想根据官方提供的
playground
摘录翻译一下现在的版本的函数,目前我下载是的是3.5.0版本
0. 前言
援引以前以前学习的一篇文章的前期准备工作
SupportCode
在进入正题之前,先看下项目里的SupportCode.swift
,主要为 playground 提供了两个便利函数。一个是example
函数,专门用来写示例代码的,统一输出log
便于标记浏览,同时还能保持变量不污染全局
swift
public func example(description: String, action: () -> ()) {
print("\n--- \(description) example ---")
action()
}
另一个是delay函数,通过dispatch_after用来演示延时的:
swift
public func delay(delay:Double, closure:()->()) {
dispatch_after(
dispatch_time(
DISPATCH_TIME_NOW,
Int64(delay * Double(NSEC_PER_SEC))
),
dispatch_get_main_queue(), closure)
}
下面开始正式进入官方playground进行翻译
Creating and Subscribing to Observables
-
never
** 创建一个从不终止并且不会发生任何事件的序列 **
example("never") {
let disposeBag = DisposeBag()
let neverSequence = Observable<String>.never()
let neverSequenceSubscription = neverSequence
.subscribe { _ in
print("This will never be printed")
}
neverSequenceSubscription.disposed(by: disposeBag)
}
// 控制台
--- never example ---
- ** empty **
创建一个仅可发出Completed事件的空Observable序列。
example("empty") {
let disposeBag = DisposeBag()
Observable<Int>.empty()
.subscribe { event in
print(event)
}
.disposed(by: disposeBag)
}
// 控制台打印的结果:
--- empty example ---
completed
// 官方问答note:
本例中将创建可观察序列和订阅可观察序列链接在一起写的
-
just
创建一个只有一个事件的观察序列,参数是Element
类型,先发出next
类型的事件,最后发出complete
事件
example("just") {
let disposeBag = DisposeBag()
Observable.just("🔴")
.subscribe { event in
print(event)
}
.disposed(by: disposeBag)
}
// 控制台打印的结果
--- just example ---
next(🔴)
completed
-
of
创建具有固定数量的元素的可观察序列。
example("of") {
let disposeBag = DisposeBag()
Observable.of("🐶", "🐱", "🐭", "🐹")
.subscribe(onNext: { element in
print(element)
})
.disposed(by: disposeBag)
}
// 控制台打印结果:
--- of example ---
🐶
🐱
🐭
🐹
// 本文作者修改例子
Observable.of("🐶", "🐱", "🐭", "🐹")
.subscribe({ e in
print(e)
})
.disposed(by: disposeBag)
// 控制台打印结果:
--- of example ---
next(🐶)
next(🐱)
next(🐭)
next(🐹)
completed
以上两个例子的区别:在于打印事件和打印元素的区别,此处在官方文档出有一段解释
This example also introduces using the subscribe(onNext:) convenience method. Unlike subscribe(_:), which subscribes an event handler for all event types (Next, Error, and Completed), subscribe(onNext:) subscribes an element handler that will ignore Error and Completed events and only produce Next event elements. There are also subscribe(onError:) and subscribe(onCompleted:) convenience methods, should you only want to subscribe to those event types. And there is a subscribe(onNext:onError:onCompleted:onDisposed:) method, which allows you to react to one or more event types and when the subscription is terminated for any reason, or disposed, in a single call:
someObservable.subscribe(
onNext: { print("Element:", $0) },
onError: { print("Error:", $0) },
onCompleted: { print("Completed") },
onDisposed: { print("Disposed") }
)
大意为:
本示例还介绍了使用subscribe(onNext :)方便的方法。 不同于subscribe(_ :),它为所有事件类型(Next,Error和Completed)订阅事件处理程序,subscribe(onNext:) 订阅一个将忽略Error和Completed事件并仅生成Next事件元素的元素处理程序。 还有subscribe(onError :)和subscribe(onCompleted :)方便的方法,如果你只想订阅这些事件类型。 并且有一个订阅(onNext:onError:onCompleted:onDisposed :)方法,它允许您对一个或多个事件类型做出反应,并且当订阅由于任何原因而被终止或在一个调用中被处理时
-
from
通过一个swift的序列,比如Array,Dictionary,或者set来来创建一个观察序列
example("from") {
let disposeBag = DisposeBag()
let swiftArray = ["🐶", "🐱", "🐭", "🐹"]
Observable.from(swiftArray)
.subscribe(onNext: { print($0) })
.disposed(by: disposeBag)
}
控制台打印的结果:
--- from example ---
🐶
🐱
🐭
🐹
本例中还演示了通过通过默认参数$0代替指定的名称的参数
-
create
自定义一个观察序列,通过闭包创建,通过.on(_:)方法添加事件
example("create") {
let disposeBag = DisposeBag()
let myJust = { (element: String) -> Observable<String> in
return Observable.create { observer in
observer.on(.next(element))
observer.on(.completed)
return Disposables.create()
}
}
myJust("🔴")
.subscribe { print($0) }
.disposed(by: disposeBag)
}
// 控制台打印的结果:
--- create example ---
next(🔴)
completed
-
range
** 通过一组顺序的数值作为事件的元素创建一个观察序列,包含一个停止事件**
example("range") {
let disposeBag = DisposeBag()
Observable.range(start: 1, count: 10)
.subscribe { print($0) }
.disposed(by: disposeBag)
}
--- range example ---
next(1)
next(2)
next(3)
next(4)
next(5)
next(6)
next(7)
next(8)
next(9)
next(10)
completed
-
repeatElement
创建一个含有N个事件的序列,每个事件的元素都是相同的,通过take
关键字来限定N的次数,如果添加take
,就会一直不同的创建事件
example("repeatElement") {
let disposeBag = DisposeBag()
Observable.repeatElement("🔴")
.take(3)
.subscribe(onNext: { print($0) })
.disposed(by: disposeBag)
}
// 控制台打印的结果:
--- repeatElement example ---
🔴
🔴
🔴
-
generate
根据条件创建观察序列(个人觉得有点像for(i=0;i>0;i++))
example("generate") {
let disposeBag = DisposeBag()
Observable.generate(
initialState: 0,
condition: { $0 < 3 },
iterate: { $0 + 1 }
)
.subscribe(onNext: { print($0) })
.disposed(by: disposeBag)
}
// 控制台打印的结果:
--- generate example ---
0
1
2
-
deferred
在每次订阅的时候再创建序列,每个订阅者订阅的对象都是内容相同而完全独立的序列
example("deferred") {
let disposeBag = DisposeBag()
var count = 1
let deferredSequence = Observable<String>.deferred {
print("Creating \(count)")
count += 1
return Observable.create { observer in
print("Emitting...")
observer.onNext("🐶")
observer.onNext("🐱")
observer.onNext("🐵")
return Disposables.create()
}
}
print("第1次订阅")
deferredSequence
.subscribe(onNext: { print($0) })
.disposed(by: disposeBag)
print("第2次订阅")
deferredSequence
.subscribe(onNext: { print($0) })
.disposed(by: disposeBag)
}
// 控制台打印的结果:
--- deferred example ---
第1次订阅
Creating 1
Emitting...
🐶
🐱
🐵
第2次订阅
Creating 2
Emitting...
🐶
🐱
🐵
-
error
创建一个序列,序列没有成员,并且发出.error事件
example("error") {
let disposeBag = DisposeBag()
let error = NSError(domain: "domin", code: 0, userInfo: nil)
Observable<Int>.error(error)
.subscribe { print($0) }
.disposed(by: disposeBag)
}
// 控制台打印的结果:
--- error example ---
error(Error Domain=domin Code=0 "(null)")
-
doOn
** 监听每一个事件,监听方法在事件执行前调用**
example("doOn") {
let disposeBag = DisposeBag()
Observable.of("🍎", "🍐", "🍊", "🍋")
.do(onNext: { print("Intercepted:", $0) }, onError: { print("Intercepted error:", $0) }, onCompleted: { print("Completed") })
.subscribe(onNext: { print($0) })
.disposed(by: disposeBag)
}
// 控制台打印的结果:
--- doOn example ---
Intercepted: 🍎
🍎
Intercepted: 🍐
🍐
Intercepted: 🍊
🍊
Intercepted: 🍋
🍋
Completed
官方文档补充
There are also doOnNext(:), doOnError(:), and doOnCompleted(_:) convenience methods to intercept those specific events, and doOn(onNext:onError:onCompleted:) to intercept one or more events in a single call.
翻译为
还有doOnNext(_ :),doOnError(_ :)和doOnCompleted(_ :)方便的方法来拦截那些特定的事件,并且doOn(onNext:onError:onCompleted :)在一个调用中拦截一个或多个事件。
下一节:RxSwift文档翻译2--Working with Subjects
本文部分内容参考自
[整理]RxSwift完全入坑手册](http://www.jianshu.com/p/76211eed0ab3)