1. 程式人生 > IOS開發 >原始碼剖析:探究 Repeat 中 GCD 的應用

原始碼剖析:探究 Repeat 中 GCD 的應用

這是小專欄《徹底搞定 GCD?併發程式設計》的一篇副產品文章

簡介

RepeatDaniele 開發的一個基於 GCD - Grand Central Dispatch 的輕量定時器,可用於替代 NSTimer,解決其多項不足

特性

Daniel 著重強調的一些特性:

  • 介面簡潔明瞭不冗餘
  • 避免強引用,解決潛在的記憶體洩露問題
  • 支援註冊多個觀察者物件監聽定時器
  • 支援暫停、開始、恢復、重置等操作
  • 支援設定多種重複模式
    • infinite:無限定時重複
    • finite:有限次定時重複
    • once:單次定時執行

針對以上特性,我們接下來閱讀原始碼時可以著重看看 Daniel 是怎樣實現的。

另外,這個庫還擴充套件提供了兩個有趣的特性:

  • Debouncer: 防抖動,避免方法呼叫過於密集,總是執行每隔一定時間段內最後一個呼叫。
  • Throttler: 節流閥,確保每隔一定時間段內僅執行一次,並忽略其他呼叫。

這兩個特性對於用過 RxSwift 的開發者肯定不陌生,有了定時器,實現這兩者也是順理成章。

介面的設計、使用與實現

首先,從介面的設計來看看其是否「簡潔明瞭」、「不冗餘」,再逐步深入其內部實現。

定時器

注意:Repeater 被設計成和其他許多物件一樣,需要被持有來避免被釋放。

建立單次定時器

  • 介面設計與呼叫
// 建立單次執行定時器
log("當時只道是尋常")
self
.timer = Repeater.once(after: .seconds(5)) { timer in // 5s 後執行 log("歲月如歌,簡單愛一次") } 複製程式碼

輸出:

2019-10-14 15:12:04 +0000: 當時只道是尋常
2019-10-14 15:12:09 +0000: 歲月如歌,簡單愛一次
複製程式碼
  • 單元測試設計
func test_timer_once() {
  let exp = expectation(description: "test_once")

  let timer = Repeater.once(after: .seconds(5)) { _
in exp.fulfill() } print("Allocated timer \(timer)") wait(for: [exp],timeout: 6) } 複製程式碼

建立有限次重複的定時器

  • 介面設計與呼叫
log("當時只道是尋常")
self.timer = Repeater.every(.seconds(10),count: 5) { timer in
    // 每 10s 執行 1 次,5 次後結束
    log("歲月如歌,簡單愛一次")
}
複製程式碼

輸出:

2019-10-14 15:18:56 +0000: 當時只道是尋常
2019-10-14 15:19:06 +0000: 歲月如歌,簡單愛一次
2019-10-14 15:19:16 +0000: 歲月如歌,簡單愛一次
2019-10-14 15:19:26 +0000: 歲月如歌,簡單愛一次
2019-10-14 15:19:36 +0000: 歲月如歌,簡單愛一次
2019-10-14 15:19:46 +0000: 歲月如歌,簡單愛一次
複製程式碼
  • 單元測試設計
func test_timer_finiteAndRestart() {
  let exp = expectation(description: "test_finiteAndRestart")

  var count: Int = 0
  var finishedFirstTime: Bool = false
  let timer = Repeater(interval: .seconds(0.5),mode: .finite(5)) { _ in
    count += 1
    print("Iteration #\(count)")
  }
  timer.onStateChanged = { (_,state) in
    print("State changed: \(state)")
    if state.isFinished {
      if finishedFirstTime == false {
        print("Now restart")
        timer.start()
        finishedFirstTime = true
      } else {
        exp.fulfill()
      }
    }
  }

  timer.start()

  wait(for: [exp],timeout: 30)
}
複製程式碼

單元測試輸出:

State changed: running
State changed: executing
Iteration #1
State changed: executing
Iteration #2
State changed: executing
Iteration #3
State changed: executing
Iteration #4
State changed: executing
Iteration #5
State changed: finished
Now restart
State changed: idle/paused
State changed: running
State changed: executing
Iteration #6
State changed: executing
Iteration #7
State changed: executing
Iteration #8
State changed: executing
Iteration #9
State changed: executing
Iteration #10
State changed: finished
複製程式碼

可以看到,有限次的定時器在次數達到結束後,還可以繼續呼叫 start() 重新開始再次複用,而不必另外建立新例項。

建立無限重複定時器

  • 介面設計與呼叫
log("當時只道是尋常")
let timer = Repeater.every(.seconds(5)) { timer in
    // 每 5s 執行一次,直到 timer 生命週期結束
    log("歲月如歌,簡單愛一次")
}
複製程式碼

輸出:

2019-10-14 15:24:05 +0000: 當時只道是尋常
2019-10-14 15:24:10 +0000: 歲月如歌,簡單愛一次
2019-10-14 15:24:15 +0000: 歲月如歌,簡單愛一次
2019-10-14 15:24:20 +0000: 歲月如歌,簡單愛一次
2019-10-14 15:24:25 +0000: 歲月如歌,簡單愛一次
2019-10-14 15:24:30 +0000: 歲月如歌,簡單愛一次
2019-10-14 15:24:35 +0000: 歲月如歌,簡單愛一次
2019-10-14 15:24:40 +0000: 歲月如歌,簡單愛一次
2019-10-14 15:24:45 +0000: 歲月如歌,簡單愛一次
...
複製程式碼
  • 單元測試設計
func test_timer_infinite() {
  let exp = expectation(description: "test_once")

  var count: Int = 0
  let timer = Repeater.every(.seconds(0.5),{ _ in
    count += 1
    if count == 20 {
      exp.fulfill()
    }
  })

  print("Allocated timer \(timer)")
  wait(for: [exp],timeout: 10)
}
複製程式碼

手動管理計時器

  • 介面設計與呼叫
log("當時只道是尋常")
self.timer = Repeater(interval: .seconds(5),mode: .infinite) { _ in
    // 每 5s 執行一次,直到 timer 生命週期結束
    log("歲月如歌,簡單愛一次")
}
timer.start()
複製程式碼

輸出:

2019-10-14 23:13:46 +0000: 當時只道是尋常
2019-10-14 23:13:51 +0000: 歲月如歌,簡單愛一次
2019-10-14 23:13:56 +0000: 歲月如歌,簡單愛一次
2019-10-14 23:14:01 +0000: 歲月如歌,簡單愛一次
2019-10-14 23:14:06 +0000: 歲月如歌,簡單愛一次
2019-10-14 23:14:11 +0000: 歲月如歌,簡單愛一次
2019-10-14 23:14:16 +0000: 歲月如歌,簡單愛一次
2019-10-14 23:14:21 +0000: 歲月如歌,簡單愛一次
2019-10-14 23:14:26 +0000: 歲月如歌,簡單愛一次
...
複製程式碼

其他方法:

  • start(): 開始一個已暫停或新建立的定時器
  • pause():暫停一個正在執行的定時器
  • reset(_ interval: Interval,restart: Bool):重置一個正在執行的定時器,更改時間間隔並重新開始
  • fire():額外手動呼叫一次定時器繫結事件

屬性:

  • .mode:定時器型別模式
    • infinite:無限定時重複
    • finite:有限次定時重複
    • once:單次定時執行
  • .remainingIterations:針對 .finite 有限次重複模式結束前的剩餘迭代次數

新增或移除多個定時處理

一般而言,初始化定時器時會指定一個處理方法。除此之外, Repeat 的定時器還支援通過observe()額外新增處理方法,並且支援通過token再移除。

// 新增額外的處理監聽
let token = timber.observe { _ in
	// 額外的新處理
  log("一個鬧鐘能夠同時叫醒相愛的兩個人。")
}
timer.start()

// 移除
timer.remove(token)
複製程式碼

觀察定時器的狀態變化

每個定時器維護著一個狀態機,處在以下某個狀態:

  • .paused:空閒(未被開始過)或已暫停
  • .running:正在計時中
  • .executing:註冊的定時處理方法正在執行
  • .finished:計時結束

可以通過.onStateChanged屬性新增狀態變化回撥監聽:

timer.onStateChanged = { timer,newState in
    // 觀察定時器狀態變化並做相應處理
    log("你永遠叫不醒一個裝睡的人")
}
複製程式碼

防抖動器

TBD

節流閥

TBD

原始碼探究

接下來,進一步看看以上的介面都是如何實現的吧。

檔案目錄結構

.
├── CHANGELOG.md
├── Configs
│   ├── Repeat.plist
│   └── RepeatTests.plist
├── LICENSE
├── Package.swift
├── README.md
├── Repeat.podspec
├── Repeat.xcodeproj
├── Sources
│   └── Repeat
│       ├── Debouncer.swift
│       ├── Repeater.swift
│       └── Throttler.swift
└── Tests
    ├── LinuxMain.swift
    └── RepeatTests
        └── RepeatTests.swift
複製程式碼

主要檔案:

類圖與方法概覽

工廠類方法實現以及與 Timer 的異同

介面設計與使用中可以看到,Repeater 提供了便捷工廠類方法,並且生成的定時器都會「自動開始」,與 Timer 的工廠類方法相似:

/// Alternative API for timer creation with a block.
/// - Experiment: This is a draft API currently under consideration for official import into Foundation as a suitable alternative to creation via selector
/// - Note: Since this API is under consideration it may be either removed or revised in the near future
/// - Warning: Capturing the timer or the owner of the timer inside of the block may cause retain cycles. Use with caution
open class func scheduledTimer(withTimeInterval interval: TimeInterval,repeats: Bool,block: @escaping (Timer) -> Void) -> Timer {
    let timer = Timer(fire: Date(timeIntervalSinceNow: interval),interval: interval,repeats: repeats,block: block)
    CFRunLoopAddTimer(CFRunLoopGetCurrent(),timer._timer!,kCFRunLoopDefaultMode)
    return timer
}
複製程式碼

?Tips & Declaration: Timer.swift,註釋中有特別提醒注意迴圈引用的問題。

對比一下 Repeater 的類工廠方法實現:

/// Create and schedule a timer that will call `handler` once after the specified time.
///
/// - Parameters:
///   - interval: interval delay for single fire
///   - queue: destination queue,if `nil` a new `DispatchQueue` is created automatically.
///   - observer: handler to call when timer fires.
/// - Returns: timer instance
@discardableResult
public class func once(after interval: Interval,tolerance: DispatchTimeInterval = .nanoseconds(0),queue: DispatchQueue? = nil,_ observer: @escaping Observer) -> Repeater {
      let timer = Repeater(interval: interval,mode: .once,tolerance: tolerance,queue: queue,observer: observer)
  timer.start()
  return timer
}

/// Create and schedule a timer that will fire every interval optionally by limiting the number of fires.
///
/// - Parameters:
///   - interval: interval of fire
///   - count: a non `nil` and > 0  value to limit the number of fire,`nil` to set it as infinite.
///   - queue: destination queue,if `nil` a new `DispatchQueue` is created automatically.
///   - handler: handler to call on fire
/// - Returns: timer
@discardableResult
public class func every(_ interval: Interval,count: Int? = nil,_ handler: @escaping Observer) -> Repeater {
  let mode: Mode = (count != nil ? .finite(count!) : .infinite)
      let timer = Repeater(interval: interval,mode: mode,observer: handler)
  timer.start()
  return timer
}
複製程式碼

兩者的做法大相徑庭,都是建立一個定時器例項並「自動開始」,只是開始的方式由於內部固有的實現方式有所不同:

  • Timer 依賴 RunLoop,需要將建立定時器生成的 CFRunLoopTimer 加入當前 Runloop
  • Repeater 依賴 GCD 的 DispatchSourceTimerstart 內部會調 DispatchSourceTimer 的 例項方法resume

初始化方法

/// Initialize a new timer.
///
/// - Parameters:
///   - interval: interval of the timer
///   - mode: mode of the timer
///   - tolerance: tolerance of the timer,0 is default.
///   - queue: queue in which the timer should be executed; if `nil` a new queue is created automatically.
///   - observer: observer
public init(interval: Interval,mode: Mode = .infinite,tolerance: DispatchTimeInterval = .nanoseconds(0),queue: DispatchQueue? = nil,observer: @escaping Observer) {
  self.mode = mode
  self.interval = interval
  self.tolerance = tolerance
  self.remainingIterations = mode.countIterations
  self.queue = (queue ?? DispatchQueue(label: "com.repeat.queue"))
  self.timer = configureTimer()
  self.observe(observer)
}
複製程式碼

初始化方法引數列表:

  • interval:定時器時間間隔
  • mode:定時器重複模式,預設為.infinite,無限重複
  • tolerance:容許誤差(這個最終是作為DispatchSourceTimerleeway引數)
  • queue:指定定時器執行的佇列,若未指定,則自動建立預設佇列
  • observer:定時器執行的回撥方法

建立並配置 DispatchSourceTimer

private func configureTimer() -> DispatchSourceTimer {
  let associatedQueue = (queue ?? DispatchQueue(label: "com.repeat.\(NSUUID().uuidString)"))
  let timer = DispatchSource.makeTimerSource(queue: associatedQueue)
  let repeatInterval = interval.value
  let deadline: DispatchTime = (DispatchTime.now() + repeatInterval)
  if self.mode.isRepeating {
    timer.schedule(deadline: deadline,repeating: repeatInterval,leeway: tolerance)
  } else {
    timer.schedule(deadline: deadline,leeway: tolerance)
  }

  timer.setEventHandler { [weak self] in
    if let unwrapped = self {
      unwrapped.timeFired()
    }
  }
  return timer
}
複製程式碼
  • 根據初始化傳入的引數,初始化並配置一個 DispatchSourceTimer
  • 將 DispatchSourceTimer 的處理回撥通過timeFired方法處理

這一段程式碼是 Repeat 中 GCD 的應用關鍵,Repeat 的核心計時器即是 DispatchSourceTimer,進一步封裝並遮蔽部分複雜邏輯,以提供簡潔易用的介面。

計時器啟動、暫停與重置

/// Reset the state of the timer,optionally changing the fire interval.
///
/// - Parameters:
///   - interval: new fire interval; pass `nil` to keep the latest interval set.
///   - restart: `true` to automatically restart the timer,`false` to keep it stopped after configuration.
public func reset(_ interval: Interval?,restart: Bool = true) {
  if self.state.isRunning {
    self.setPause(from: self.state)
  }

  // For finite counter we want to also reset the repeat count
  if case .finite(let count) = self.mode {
    self.remainingIterations = count
  }

  // Create a new instance of timer configured
  if let newInterval = interval {
    self.interval = newInterval
  } // update interval
  self.destroyTimer()
  self.timer = configureTimer()
  self.state = .paused

  if restart {
    self.timer?.resume()
    self.state = .running
  }
}

/// Start timer. If timer is already running it does nothing.
@discardableResult
public func start() -> Bool {
  guard self.state.isRunning == false else {
    return false
  }

  // If timer has not finished its lifetime we want simply
  // restart it from the current state.
  guard self.state.isFinished == true else {
    self.state = .running
    self.timer?.resume()
    return true
  }

  // Otherwise we need to reset the state based upon the mode
  // and start it again.
  self.reset(nil,restart: true)
  return true
}

/// Pause a running timer. If timer is paused it does nothing.
@discardableResult
public func pause() -> Bool {
  guard state != .paused && state != .finished else {
    return false
  }

  return self.setPause(from: self.state)
}

/// Pause a running timer optionally changing the state with regard to the current state.
///
/// - Parameters:
///   - from: the state which the timer should only be paused if it is the current state
///   - to: the new state to change to if the timer is paused
/// - Returns: `true` if timer is paused
@discardableResult
private func setPause(from currentState: State,to newState: State = .paused) -> Bool {
  guard self.state == currentState else {
    return false
  }

  self.timer?.suspend()
  self.state = newState

  return true
}
複製程式碼
  • start方法主要是做狀態判斷並進行相應處理返回結果,其開始計時的核心是呼叫內部 DispatchSourceTimerresume 方法
  • pause 方法類似,呼叫的是 suspend 方法,並更新內部計時器狀態
  • reset 重置內部的一些計時標誌位的同時,會將內部的 DispatchSourceTimer 銷燬並新建

新增或移除多個定時觀察者

/// List of the observer of the timer
private var observers = [ObserverToken: Observer]()

/// Next token of the timer
private var nextObserverID: UInt64 = 0

/// Add new a listener to the timer.
///
/// - Parameter callback: callback to call for fire events.
/// - Returns: token used to remove the handler
@discardableResult
public func observe(_ observer: @escaping Observer) -> ObserverToken {
  var (new,overflow) = self.nextObserverID.addingReportingOverflow(1)
  if overflow { // you need to add an incredible number of offset...sure you can't
    self.nextObserverID = 0
    new = 0
  }
  self.nextObserverID = new
  self.observers[new] = observer
  return new
}

/// Remove an observer of the timer.
///
/// - Parameter id: id of the observer to remove
public func remove(observer identifier: ObserverToken) {
  self.observers.removeValue(forKey: identifier)
}
複製程式碼
  • 通過字典儲存觀察者回調事件,通過 UInt64 的 ObserverToken 來進行標識
  • 觀察者數量上限控制在 UInt64 的溢位範圍

定時事件觸發

/// Called when timer is fired
private func timeFired() {
  self.state = .executing

  if case .finite = self.mode {
    self.remainingIterations! -= 1
  }

  // dispatch to observers
  self.observers.values.forEach { $0(self) }

  // manage lifetime
  switch self.mode {
  case .once:
    // once timer's lifetime is finished after the first fire
    // you can reset it by calling `reset()` function.
    self.setPause(from: .executing,to: .finished)
  case .finite:
    // for finite intervals we decrement the left iterations count...
    if self.remainingIterations! == 0 {
      // ...if left count is zero we just pause the timer and stop
      self.setPause(from: .executing,to: .finished)
    }
  case .infinite:
    // infinite timer does nothing special on the state machine
    break
  }

}
複製程式碼
  • timeFired 方法被兩個地方呼叫,一個是配置DispatchSourceTimer時設定的事件回撥,一個是對外暴露的手動觸發方法 fire(andPause:)
  • 根據計時模式更新計時器狀態,計時模式的實現核心邏輯即在於此
  • 遍歷所有觀察者逐個回撥,觸發真正的計時器繫結事件

總結

Repeat Mind Map

致謝與參考

文中涉及原始碼大部分來自開源社群,以及部分其他文獻參考。