— Android, Jetpack, Compose, Kotlin — 1 min read
Here's a quick tip about doing something with a delay in Jetpack Compose - using LaunchedEffect
.
As a quick refresher, LaunchedEffect allows you to run some code on your first composition - or every time a specific key changes:
1// Just once(but will be called again if you are using navigation and pop back etc.)2LaunchedEffect(Unit) {3 // Do something...4}5
6// With a key7LaunchedEffect(key) {8 // Do something...9}
If you're new to Compose you might be surprised to learn that you can actually just add a delay call to the code inside your LaunchedEffect
:
1// Just once2LaunchedEffect(Unit) {3 delay(10.seconds)4 // Do something...5}
And you're good to go! It's also worth keeping in mind that LaunchedEffect
runs your code in a coroutine scope - so you won't get any warnings about using delay like you would if you were just using a normal(not suspended) function. I also wrote another post last week about using derivedStateOf
, you can check it out here!