我正在创建一个登录令牌有效性计时器,我认为它需要是一个单例,每秒钟(或每分钟或任何时间),检查登录令牌是否仍然有效。
但是我甚至不能让单例模式每秒打印一条消息。为什么不呢?
import SwiftUI
import Combine
class TokenObserver: ObservableObject {
private let publisher = Timer.TimerPublisher(interval: 1.0, runLoop: .main, mode: .default)
private let cancellable: AnyCancellable?
static let instance = TokenObserver()
let uuid = UUID()
private init() {
NSLog("TokenObserver.init()")
self.cancellable = self.publisher.sink(receiveCompletion: { completion in
NSLog("TokenObserver (completion)")
}, receiveValue: { date in
NSLog("TokenObserver timestamp=" + ISO8601DateFormatter().string(from: date))
})
}
deinit {
NSLog("TokenObserver.deinit()")
self.cancellable?.cancel()
}
}
struct ContentView: View {
var body: some View {
Text("Hello, world! Instance = " + TokenObserver.instance.uuid.uuidString)
.padding()
}
}
您必须在Timer
发布器上调用autoconnect()
来启动它。
private init() {
NSLog("TokenObserver.init()")
self.cancellable = self.publisher.autoconnect().sink(receiveCompletion: { completion in
NSLog("TokenObserver (completion)")
}, receiveValue: { date in
NSLog("TokenObserver timestamp=" + ISO8601DateFormatter().string(from: date))
})
}