https://kotlinlang.org logo
#compose-android
Title
# compose-android
u

uli

10/12/2023, 4:34 PM
Hi there, I have done some testing, regarding ComposeView.setContent and entering a new composition:
Copy code
fun setupCompose(val value: Int) {
    composeView.setContent {
        LaunchedEffect(kotlin.Unit) {
            println("Uli: Effect Launched")
        }
        MyValueView(value)
    }
}

var myValue = 0
repeat(10) { setupCompose(myValue++) }
I was suspecting the effect to fire 10 times, as the composable is being setup from scratch. Well, it didn’t. It fired only once. Now I am wondering, if anything, could break the optimization and actually lead to the effect firing 10 times, or if I can rest assured that resetting the composeView’s content does not enter a new composition
p

Pablichjenkov

10/12/2023, 4:53 PM
Why would you expect that? The Effect lambda just copy whatever it references once and survive across recompositions. You need to key it if you want to update.
Kinda similar behavior as remember
u

uli

10/12/2023, 4:54 PM
i was expecting that when I pass a new lambda into setContent, it would start from scratch
p

Pablichjenkov

10/12/2023, 4:56 PM
For that you have
SideEffect
which executes per recomposition but LaunchEffect runs only once when the Composable enters the composition tree
u

uli

10/12/2023, 4:56 PM
And I was thinking, setContent would make it enter the composition again. I.e. remove it and insert it.
p

Pablichjenkov

10/12/2023, 4:57 PM
If you reference State inside LaunchEffect is a good practice use it as key
u

uli

10/12/2023, 4:58 PM
@Pablichjenkov, thanks, I am aware of that. I did the tests more for optimization and thought I should not call setContent multiple times. I am postively surprised, that the effect is called only once
p

Pablichjenkov

10/12/2023, 5:03 PM
I got you now, I was actually thinking of setContent as a general example not the real one. In this case my theory is that once the composer tree starts, whatever update it receives later it will continue diffing it against whatever it had before, if there was anything. It won't fully update but keeps diffing as any other composable function. The
set
part in the name is probably misleading i guess
u

uli

10/12/2023, 5:12 PM
thx
a

Albert Chang

10/13/2023, 12:48 AM
I believe it's because you are setting the content in the same frame. Composition won't start until a new frame.
💡 1
🎣 1
u

uli

10/13/2023, 4:54 AM
Same if I put delay(1000) between
But good catch
z

Zach Klippenstein (he/him) [MOD]

10/13/2023, 12:59 PM
I’m not sure if it’s part of setContent’s contract that it doesn’t create a brand new composition. But if you need that strong guarantee, just use AbstractComposeView. Then you implement an abstract method to define your composable, and can implement that guarantee yourself.
3 Views