Created
October 16, 2025 01:45
-
-
Save lgawin/f8dbe256dd5e5a02af17cb6ae40cd61d to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| package dev.gawluk | |
| import android.os.SystemClock | |
| import java.time.Clock | |
| import java.time.Instant | |
| import java.time.ZoneId | |
| import java.time.temporal.ChronoUnit | |
| fun monotonicClock(zone: ZoneId): Clock = MonotonicClock(zone) | |
| private class MonotonicClock(private val zone: ZoneId) : Clock() { | |
| private val initialInstant = Clock.system(zone).instant() | |
| private val initialElapsedNanos: Long = SystemClock.elapsedRealtimeNanos() | |
| private val initialMillis = System.currentTimeMillis() | |
| private val initialElapsedMillis: Long = SystemClock.elapsedRealtime() | |
| override fun getZone(): ZoneId = zone | |
| override fun withZone(zone: ZoneId): Clock { | |
| if (zone == this.zone) { | |
| return this | |
| } | |
| return MonotonicClock(zone) | |
| } | |
| override fun instant(): Instant { | |
| val elapsedNanos: Long = SystemClock.elapsedRealtimeNanos() - initialElapsedNanos | |
| return initialInstant.plus(elapsedNanos, ChronoUnit.NANOS) | |
| } | |
| // optimization to avoid Instant object creation | |
| override fun millis(): Long { | |
| return initialMillis + (SystemClock.elapsedRealtime() - initialElapsedMillis) | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment