组合定时器-设置定时器



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

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: { [weak self] value in
self?.update(date: value)
})
}

func update(date: Date) {
self.somedate = date
print(self.somedate)
}
}

最新更新