Skip to content

Instantly share code, notes, and snippets.

@adamp
Last active December 20, 2024 03:11
Show Gist options
  • Save adamp/e69593c28fa8642bd7eee22bb4a733ee to your computer and use it in GitHub Desktop.
Save adamp/e69593c28fa8642bd7eee22bb4a733ee to your computer and use it in GitHub Desktop.
Working with animation frame time in Jetpack Compose
/**
* 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
}
@hakanai
Copy link

hakanai commented Feb 20, 2022

  • launchInComposition is now LaunchedEffect(Unit)
  • LifecycleOwnerAmbient is now LocalLifecycleOwner and has moved to a separate library
  • awaitFrameMillis is now withFrameMillis
  • whenStarted is now deprecated - replacement is withStarted
  • The code inside the while block is now invalid because withStarted does not execute its context in a coroutine.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment