我创建了一个使用 ObservableObject
的视图,该视图使用 Timer
更新作为 @Published
属性的秒数。
class TimerService: ObservableObject {
@Published var seconds: Int
var timer: Timer?
convenience init() {
self.init(0)
}
init(_ seconds: Int){
self.seconds = seconds
}
func start() {
...
self.timer = Timer.scheduledTimer(withTimeInterval: 1,repeats: true) { _ in
self.seconds += 1 }
self.timer?.fire()
}
func stop() {...}
func reset() {...}
}
为了测试这个逻辑,我尝试订阅 seconds
变量。问题是 .sink 方法只触发一次,永远不会再触发,即使它应该触发。
class WorkTrackerTests: XCTestCase {
var timerService: TimerService!
override func setUpWithError() throws {
super.setUp()
timerService = TimerService()
}
override func tearDownWithError() throws {
super.tearDown()
timerService = nil
}
func test_start_timer() throws {
var countingArray: [Int] = []
timerService.start()
timerService.$seconds.sink(receiveValue: { value -> Void in
print(value) // 1 (called once with this value)
countingArray.append(value)
})
timerService.stop()
for index in 0...countingArray.count-1 {
if(index>0) {
XCTAssertTrue(countingArray[index] - 1 == countingArray[index-1])
}
}
}
}
是我做错了什么,还是 SwiftUI @Published Wrapper 不能被 SwiftUI 本身以外的其他东西订阅?