Home > AI > IOS > Combine >

Timer.publish

Example 1: repeat the code execution after a period
(how to cancel the timer publisher, how to connect it with the text)

struct GoodView: View {
    let timer = Timer.publish(every: 5, on: .main, in: .common).autoconnect()
    @State private var counter = 0
    @State var content: String = "Hello World"

    var body: some View {
        Text("\(content)")
            .onReceive(timer) { time in
                if self.counter == 5 {
                   self.timer.upstream.connect().cancel()
                } else {
                    content = "The time is now \(time)"
                }

                self.counter += 1
            }
    }
}

Example 2:

class Demo13 {
    var subscriptions = Set<AnyCancellable>()
    
    let start = Date()
    let deltaFormatter: NumberFormatter = {
        let f = NumberFormatter()
        f.negativePrefix = ""
        f.minimumFractionDigits = 1
        f.maximumFractionDigits = 1
        return f
    }()
    

/// 本页代码运行时初始化时间, 计算运行到固定行数时得到时间差
    public var deltaTime: String {
        return deltaFormatter.string(for: Date().timeIntervalSince(start))!
    }

 
    
    func example(of: String) {
        // save to variable to make it alive
        let pub = Timer.publish(every: 5, on: .main, in: .common).autoconnect()

        pub.sink { [self] date in
            print("origin:\t" + "\(deltaTime)\t" + date.description)
        }.store(in: &subscriptions)

        
        pub.delay(for: .seconds(2), scheduler: DispatchQueue.main)
            .sink { [self] date in
                print("delay:\t" + "\(deltaTime)\t" + date.description)
            }
            .store(in: &subscriptions)
    }
}


let d = Demo13()
d.example(of: "good")

Leave a Reply