序列有很多种类,用对了序列就会有事半功倍的效果。这个篇章总结一下常用序列的创建:
1.emty
空序列创建
Observable<String>.empty()
.subscribe(onNext: { (text) in
print(text)
}
2.just
单个信号序列创建
Observable<[String]>.just(["a","b","c"])
.subscribe(onNext: { (text) in
print(text)
}
3.of
多个元素
Observable<String>.of("a","b")
.subscribe(onNext: { (text) in
print(text)
}
Observable<[String]>.of(["a","b"])
.subscribe(onNext: { (text) in
print(text)
}
Observable<[String: String]>.of(["a": "1", "b": "2"])
.subscribe(onNext: { (text) in
print(text)
}
4.from
从集合中获取序列,可选项处理更安全
Observable<[String]>.from(optional: ["a","b"])
.subscribe(onNext: { (text) in
print(text)
}
5.deferred
deferred
延迟序列的初始化,通过传入的闭包来实现初始化
var isTrue = true
Observable<String>.deferred { () -> Observable<String> in
if isTrue {
return Observable.of("1","2")
}
return Observable.of("a","b")
}.subscribe(onNext: { (text) in
print(text)
}
6.range
生成指定范围内的可观察整数序列
Observable.range(start: 1, count: 5)
.subscribe(onNext: { (num) in
print(num)
}
7.range
只有当所有的判断条件都符合的时候,才会响应的序列。会先判断条件1,再判断条件2,然后一直递归下去,直到有条件不满足
Observable.generate(initialState: 0, // 初始值
condition: { $0 < 8}, // 条件1
iterate: { $0 + 1 }) // 条件2
.subscribe(onNext: { (num) in
print(num)
}
8.repeatElement
可以无限发出给定元素的序列
Observable<Int>.repeatElement(5)
.subscribe(onNext: { (num) in
print(num)
}
9.error
错误序列
Observable<String>.error(NSError.init(domain: "err", code: 888, userInfo: nil))
.subscribe(onError: { (err) in
print(err)
})
10.never
永远不会发送事件也不会终止的序列
Observable<String>.never()
.subscribe(onNext: { (num) in
print(num)
}
11.create
基础序列
Observable<String>.create{observer in
observer.onNext("发送")
observer.onCompleted()
return Disposables.create()
}.subscribe(onNext: { (text) in
print(text)
}
12.timer
定时器
Observable<Int>.timer(1, scheduler: MainScheduler.instance)
.subscribe(onNext: { (num) in
print(num)
}
13.interval
定时器
Observable<Int>.interval(1, scheduler: MainScheduler.instance)
.subscribe(onNext: { (num) in
print(num)
}