Combine Timer - 设置定时器

Combine Timer - setting timer

我对 Combine 的 Timer.publish(every:, on: , in: ) 不是很熟悉。本质上,我正在寻找 运行 一个计时器来调用我的 ObservableObject class 中的函数。有没有更好的方法来做到这一点,不确定我这样做是否正确,或者是否有更干净的方法来做同样的事情。

class Example : ObservableObject {
    private var cancellables = Set<AnyCancellable>()
    var cancellable: AnyCancellable? = nil
    
    @Published var somedate: Date = Date()
    
    init() {
        cancellable = Timer
            .publish(every: 1, on: .main, in: .common)
            .autoconnect()
            .sink(receiveValue: { _ in
                self.update()
            })
    }
    
    func update() {
        let publisher =  Date()
        Just(publisher)
            .sink(receiveCompletion: { completion in
            }, receiveValue: { date in
                self.somedate = date
                print(self.somedate)
            }).store(in: &cancellables)
    }
}

输出似乎是正确的。

2021-08-10 22:25:24 +0000
2021-08-10 22:25:25 +0000
2021-08-10 22:25:26 +0000
2021-08-10 22:25:27 +0000
2021-08-10 22:25:28 +0000
2021-08-10 22:25:29 +0000
2021-08-10 22:25:30 +0000
2021-08-10 22:25:31 +0000
2021-08-10 22:25:32 +0000
2021-08-10 22:25:33 +0000
2021-08-10 22:25:34 +0000
2021-08-10 22:25:35 +0000
2021-08-10 22:25:36 +0000

您可以显着降低 update 函数的复杂性。无需使用 Just 创建新的发布者来获取日期。另外,您已经可以在初始 sink:

中获得它
class Example : ObservableObject {
    private var cancellable: AnyCancellable? = nil
    
    @Published var somedate: Date = Date()
    
    init() {
        cancellable = Timer
            .publish(every: 1, on: .main, in: .common)
            .autoconnect()
            .sink(receiveValue: { value in
                self.update(date: value)
            })
    }
    
    func update(date: Date) {
        self.somedate = date
        print(self.somedate)
    }
}