Last active
December 20, 2024 03:11
-
-
Save adamp/e69593c28fa8642bd7eee22bb4a733ee to your computer and use it in GitHub Desktop.
Working with animation frame time in Jetpack Compose
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
/** | |
* Returns a [State] holding a local animation time in milliseconds. | |
* The value always starts at `0L` and stops updating when | |
* the call leaves the composition. | |
*/ | |
@Composable | |
fun animationTimeMillis(): State<Long> { | |
val millisState = state { 0L } | |
val lifecycleOwner = LifecycleOwnerAmbient.current | |
launchInComposition { | |
val startTime = awaitFrameMillis { it } | |
lifecycleOwner.whenStarted { | |
while (true) { | |
awaitFrameMillis { frameTime -> | |
millisState.value = frameTime - startTime | |
} | |
} | |
} | |
} | |
return millisState | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
launchInComposition
is nowLaunchedEffect(Unit)
LifecycleOwnerAmbient
is nowLocalLifecycleOwner
and has moved to a separate libraryawaitFrameMillis
is nowwithFrameMillis
whenStarted
is now deprecated - replacement iswithStarted
withStarted
does not execute its context in a coroutine.