Last active
November 11, 2022 13:49
-
-
Save wiryadev/03022d62c802caf59ed2976ddffdb4bb to your computer and use it in GitHub Desktop.
This file contains 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
import kotlinx.coroutines.delay | |
import kotlinx.coroutines.flow.flow | |
import kotlinx.coroutines.runBlocking | |
import kotlinx.datetime.* | |
fun main(args: Array<String>) { | |
runBlocking { | |
timerPerMinute().collect { | |
println("collect: $it") | |
} | |
} | |
} | |
fun timerPerMinute() = flow { | |
val currentMillis = Clock.System.now().toEpochMilliseconds() | |
val nextOneMinuteDateTime = Clock.System.now().plus(1, DateTimeUnit.MINUTE) | |
.toLocalDateTime(TimeZone.currentSystemDefault()) | |
val nextOneMinuteInMillis = nextOneMinuteDateTime.truncateToMinute().toEpochMilliseconds() | |
// subtract to find first time difference in milis for initial delay | |
val timeDifferenceMilis = nextOneMinuteInMillis - currentMillis | |
var firstTime = true | |
println("nextDateTimeSecond: $nextOneMinuteInMillis") | |
println("dateTime: $currentMillis") | |
println("oneMinuteLater: $timeDifferenceMilis") | |
while (true) { | |
val now = Clock.System.now() | |
emit(getHourAndMinute(now)) | |
val delayAmount = if (firstTime) (timeDifferenceMilis) else 60000 | |
println("delayAmount: $delayAmount") | |
firstTime = false | |
delay(delayAmount) | |
} | |
} | |
fun LocalDateTime.truncateToMinute(): LocalDateTime = LocalDateTime( | |
year = year, | |
month = month, | |
dayOfMonth = dayOfMonth, | |
hour = hour, | |
minute = minute, | |
second = 0, | |
) | |
fun LocalDateTime.toEpochMilliseconds( | |
timeZone: TimeZone = TimeZone.currentSystemDefault() | |
) = this.toInstant(timeZone).toEpochMilliseconds() | |
fun getHourAndMinute( | |
instant: Instant, | |
timeZone: TimeZone = TimeZone.currentSystemDefault(), | |
): String { | |
val time = instant.toLocalDateTime(timeZone).time | |
val hour = formatDoubleDigitTime(time.hour) | |
val minute = formatDoubleDigitTime(time.minute) | |
return "$hour:$minute" | |
} | |
private fun formatDoubleDigitTime(time: Int) = if (time > 9) time.toString() else "0$time" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment