Code for this example One thing that you have to keep in mind with LaunchedEffect is that it will "cache" any lambdas that you pass to it. This can be a problem if you have a long-running operation running with LaunchedEffect.
LaunchedEffect relaunches only when the key changes. Once it starts, you can no longer change anything in your lambdas.
Suppose you have something like this:
What if the values inside the lambda are no longer relevant? What if you need to change it? Well, you're in luck cause "rememberUpdatedState" is here to save you!
In the example in the video, I'm demonstrating how rememberUpdatedState works with LaunchedEffect.
In the first part of the example I'm "scheduling" a lambda that will run after 6 seconds with message "foo". All this lambda is doing is just returning a String like so:
val scheduledMessage = { "foo" }
Then I'm scheduling a new lambda to be sent after 3 seconds with message "bar". After the timer runs out I expect to see the new message in the result, but this doesn't happen. That's because LaunchedEffect cached the initial lambda with the "foo" as its value.
In the 2nd part of the example I'm doing exactly the same thing, but now I'm using rememberUpdatedState() to store the lambda. The result is a proper update of the lambda inside LaunchedEffect. This in turn causes the correct message "bar" to be displayed.
So, make sure you're using rememberUpdatedState() whenever you need to have a lambda updated in your LaunchedEffect!
If you want to play around with the code - it's here. ------------------------------------------------------------------------------------------------------------
🚀 Always be learning! Have you encountered similar issues in your projects? Share your experiences below! 👇
Comentarios