LoginSignup
0
1

More than 1 year has passed since last update.

[Swift][Combine]ON/OFF切り替えありのTimer の実装方法(暫定)

Last updated at Posted at 2021-05-30

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

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1