首先需要導(dǎo)入第三方庫RxSwift
import Foundation
import RxSwift
extension Observable where Element: FloatingPoint {
/**
用 Rx 封裝的 Timer
# 用法 #
```swift
Observable<TimeInterval>.timer(duration: 5, interval: 1)
.subscribe(
onNext: { remain in
print("剩余:", remain)
},
onCompleted: {
print("計(jì)時(shí)結(jié)束!")
}
)
.disposed(by: disposeBag)
```
## 結(jié)果 ##
```swift
剩余: 5.0
剩余: 4.0
剩余: 3.0
剩余: 2.0
剩余: 1.0
剩余: 0.0
計(jì)時(shí)結(jié)束凡桥!
```
- parameter duration: 總時(shí)長
- parameter interval: 時(shí)間間隔
- parameter ascending: true 為順數(shù)計(jì)時(shí)冬三,false 為倒數(shù)計(jì)時(shí)
*/
public static func timer(duration: RxTimeInterval = RxTimeInterval.infinity, interval: RxTimeInterval = 1, ascending: Bool = false, scheduler: SchedulerType = MainScheduler.instance)
-> Observable<TimeInterval> {
let count = (duration == RxTimeInterval.infinity) ? .max : Int(duration / interval) + 1
return Observable<Int>.timer(0, period: interval, scheduler: scheduler)
.map { TimeInterval($0) * interval }
.map { ascending ? $0 : (duration - $0) }
.take(count)
}
}