Swift でON/OFF切り替えありのTimer実装に関して、既存の書き方とCombine利用時の書き方の比較。
*本当にこれで良いのかあまり自信はありません。より良い方法ありましたらコメントいただけますと幸いです。
非Combine
class ViewController: UIViewController {
private var timer: Timer?
func startTimer() {
timer = Timer.scheduledTimer(
timeInterval: 1.0,
target: self,
selector: #selector(self.periodicalFunction),
userInfo: nil,
repeats: true)
}
func stopTimer() {
timer?.invalidate()
}
@objc func periodicalFunction() {
print("update")
}
}
Combine
class ViewController: UIViewController {
private var timerCancelable: AnyCancellable?
func startTimer() {
timerCancelable = Timer.publish(every: 1.0, on: .main, in: .common)
.autoconnect()
.sink(receiveValue: { _ in
self.periodicalFunction()
})
}
func stopTimer() {
timerCancelable?.cancel()
}
func periodicalFunction() {
print("update")
}
}
Combine の場合、キャンセルのため保持するのは AnyCancellable
クラスのようです。
参考:
https://developer.apple.com/documentation/combine/replacing-foundation-timers-with-timer-publishers