11import Foundation
22import Combine
33
4- internal final class HealthChecker {
4+ internal final class RunLoopHealthChecker {
55 private let healthSubject = PassthroughSubject < Health , Never > ( )
6- private let healthSignalSubject = CurrentValueSubject < Date , Never > ( Date . distantPast)
76
87 private var timerThread : Thread ?
98 private var subscription : AnyCancellable ?
109
10+ private let target : RunLoop
1111 private let warningCriteria : TimeInterval
1212 private let criticalCriteria : TimeInterval
13+ private let healthSignalInterval : TimeInterval
1314 private let healthSignalCheckInterval : TimeInterval
1415
1516 var healthStream : AnyPublisher < Health , Never > {
@@ -19,12 +20,16 @@ internal final class HealthChecker {
1920 }
2021
2122 init (
23+ target: RunLoop ,
2224 warningCriteria: Duration ,
2325 criticalCriteria: Duration ,
26+ healthSignalInterval: Duration ,
2427 healthSignalCheckInterval: Duration
2528 ) {
29+ self . target = target
2630 self . warningCriteria = warningCriteria. converted ( to: . seconds) . value
2731 self . criticalCriteria = criticalCriteria. converted ( to: . seconds) . value
32+ self . healthSignalInterval = healthSignalInterval. converted ( to: . seconds) . value
2833 self . healthSignalCheckInterval = healthSignalCheckInterval. converted ( to: . seconds) . value
2934 }
3035
@@ -39,11 +44,18 @@ internal final class HealthChecker {
3944 }
4045
4146 private func startImpl( ) {
42- self . subscription = Timer . publish ( every: self . healthSignalCheckInterval, on: RunLoop . current, in: . common)
47+ let healthSignalCheckTimer = Timer
48+ . publish ( every: self . healthSignalCheckInterval, on: RunLoop . current, in: . common)
4349 . autoconnect ( )
44- . combineLatest ( self . healthSignalSubject. receive ( on: RunLoop . current) )
50+ let healthSignalStream = Timer
51+ . publish ( every: self . healthSignalInterval, on: self . target, in: . common)
52+ . autoconnect ( )
53+ . prepend ( AnyPublisher ( Date ( ) ) . receive ( on: self . target) )
54+ . receive ( on: RunLoop . current)
55+
56+ self . subscription = healthSignalCheckTimer. combineLatest ( healthSignalStream)
4557 . compactMap { ( now: Date , lastSignal: Date ) -> TimeInterval in
46- now. timeIntervalSince ( lastSignal)
58+ return now. timeIntervalSince ( lastSignal)
4759 }
4860 . map { ( timeDiff: TimeInterval ) -> Health in
4961 switch ( timeDiff) {
@@ -69,8 +81,4 @@ internal final class HealthChecker {
6981 self . timerThread? . cancel ( )
7082 self . timerThread = nil
7183 }
72-
73- func acceptHealthSignal( ) {
74- self . healthSignalSubject. send ( Date ( ) )
75- }
7684}
0 commit comments