https://kotlinlang.org logo
u

_shtomar

11/12/2021, 11:29 PM
Is there any callback or listener to get an event when Composable rendered it’s content for first time or it’s content is changed?
n

nglauber

11/13/2021, 12:42 AM
you can achieve something similar using this:
Copy code
@Composable
fun Foo() {
    // ...
    LaunchedEffect(Unit) {
        // This code will run just on
        // the first composition
    }
}
However, if you remove
Foo
from the composition, it will be called again… For instance:
Copy code
if (someFlag) {
    Foo()
} else {
    Bar()
}
every time you set
someFlag
to true, the code inside the
LaunchedEffect
will be executed.
a

Adam Powell

11/13/2021, 12:43 AM
What are you looking to use that callback event to do? Like @nglauber mentions above you can use the effect APIs to publish data about a recomposition, but there are many ways content can change and we try very hard to make sure that as many of them as possible have fast paths that skip running as much code as possible, and depending on what you want this for you might find yourself scratching your head as to why you aren't getting a callback you expect.
u

_shtomar

11/13/2021, 12:54 AM
Thank @nglauber
I am changing content of the Composable. Basically I need a callback whenver the content of the Composable changes
k

K Merle

11/13/2021, 5:17 AM
I think in that case you can replace Unit with the value of the content. So if you want to call LaunchedEffect when title changes only, you could do
Copy code
@Composable
fun Foo() {
    // ...
    LaunchedEffect(title) {
        // This code will run just on
        // the first composition
    }
}
2 Views