Skip to content

Timer Set Up

Alina P edited this page Nov 30, 2024 · 9 revisions

W tym właśnie sęk, że Czas nie znosi, aby go zabijano. Gdybyś była z nim w dobrych stosunkach zrobiłby dla Ciebie z twoim zegarem wszystko, co byś tylko chciała

Timer Set Up

Overview

MTimer offers a few basic settings. To start it, just call the start() function (See Timer Start-Up page). However, you might want to check the timer's current state - not just when it runs out, but perhaps every specific interval. To achieve this, you can use the publish() method

Available Methods

  • func publish(every time: TimeInterval, tolerance: TimeInterval = 0.4, _ completion: @escaping (_ currentTime: MTime) -> ()) throws -> MTimer

    • Optional method with completion block that will be called every time interval
    • Configure the interval at which the timer's status will be published (see Timer State Observing page for the reference)
  • func publish(every time: TimeInterval, tolerance: TimeInterval = 0.4, currentTime: Binding<MTime>) -> throws -> MTimer

    • Optional method with Binding property that will be updated every time interval
    • Configure the interval at which the timer's status will be published (see Timer State Observing page for the reference)

Step-by-Step Guide

  1. Initialize a timer. See Timer Initialising page for the reference
  2. (Optional) Call one of the publish methods

Example with completion block

@MainActor class ViewModel {
    @Published var time: MTime = .init()
    
    func startTimer() throws {
        try MTimer(.id)
            .publish(every: 1, tolerance: 0.7, onTimeUpdate)
    }
    func onTimeUpdate(_ time: MTime) {
        self.time = time
    }
}

Example with state value

struct ExampleView: View {
    @State var time: MTime = .init()
    
    var body: some View {
        Text("\(time.toTimeInterval())")
    }
    
    func startTimer() throws {
        try MTimer(.id)
            .publish(every: 1, tolerance: 0.7, currentTime: $time)
    }
}
  1. Start the timer Timer Start-Up

See also