MobileNativeFoundation/Kronos

Request: Restore from an older value.

DevAndArtist opened this issue · 4 comments

Is it possible to make the library persist the last value on disk and restore it after an app restart?

My suggestion:

public class TimeFreeze : NSObject, NSCoding {
    
    // NOTE: `adjustedTimestamp` is not an optional anymore
    var adjustedTimestamp: TimeInterval { ... }
    
    public required init?(coder aDecoder: NSCoder) {
        
        guard
            aDecoder.containsValue(forKey: "uptime"),
            aDecoder.containsValue(forKey: "offset"),
            aDecoder.containsValue(forKey: "timestamp")
        else { return nil }
        
        self.uptime = aDecoder.decodeDouble(forKey: "uptime")
        self.timestamp = aDecoder.decodeDouble(forKey: "offset")
        self.offset = aDecoder.decodeDouble(forKey: "timestamp")
    }
    
    public func encode(with aCoder: NSCoder) {
        
        aCoder.encode(self.uptime, forKey: "uptime")
        aCoder.encode(self.timestamp, forKey: "timestamp")
        aCoder.encode(self.offset, forKey: "offset")
    }
}

public struct Clock {
    
    // NOTE: `private(set)`
    public private(set) static var stableTime: TimeFreeze?
    
    public static func restore(from other: TimeFreeze) {
        
        guard self.stableTime == nil || (self.stableTime!.adjustedTimestamp < other.adjustedTimestamp) else { return }
        
        self.stableTime = other
    }
}

What you are asking makes sense to me; the caveat though is that Kronos can't guarantee anymore that the clock is accurate since the device could be rebooted in the middle which makes me hesitant to implement this.

@Reflejo It's fine, because there is simply no better way to do so. You can provide an API note that this cannot be guaranteed. In general the clock might be off-sync after a restart of the app, so it's up to the developer to sync it again. The restored value is needed if you close your app and lose internet connection when relaunching it. Currently there is no way to get the clock ticking until the internet connection could be restored.

P.S.: Please note that I haven't tested the code that I wrote above that much. If you're going to implement this don't forget to properly test it. :)

I'd like to keep that guarantee (non nil means trustfully time). What we can do is expose a Clock.trustfullyOffset = ... so you can implement this logic on the app side.

Fixed here #22 thanks to @mallorypaine