https://kotlinlang.org logo
#compose
Title
# compose
a

Arkadii Ivanov

11/13/2020, 12:01 AM
Which approach is more idiomatic in Compose? 1 or 2?
Copy code
@Composable
fun foo1(dependency: () -> Dependency) {
    val x = remember { Bar(dependency()) }
}

@Composable
fun foo2(dependency: Dependency) {
    val x = remember { Bar(dependency) }
}
a

Adam Powell

11/13/2020, 12:05 AM
I think you may be looking for:
Copy code
@Composable
fun foo2(dependency: Dependency) {
    val x = remember(dependency) { Bar(dependency) }
}
where
x
will be the same instance so long as
dependency
doesn't change
👍 2
j

jim

11/13/2020, 12:11 AM
That assumes dependency is provably immutable, so you'd almost certainly want to go with the non-lambda variant to avoid accidental captures.
a

Arkadii Ivanov

11/13/2020, 12:23 AM
Looks like same approach is used for
Image
,
ImageAsset
interface does not look like immutable
Also found this code in Compose sources.
InteractionState
is clearly mutable.
j

jim

11/13/2020, 12:37 AM
Image and ImageAsset had better be effectively immutable or that code is going to have the wrong behavior.
The second example with remember in the default value of an optional parameter - that is very much idiomatic Compose, that is the best style of all of them, but it has different behavior from the code you mentioned originally.
The second example (good, high quality, idiomatic code) only performs the remember if a value was not provided. The second example does NOT need to be immutable.
in fact, for the second (good) example, doing the remember would be almost pointless if the remembered value were immutable.
a

Arkadii Ivanov

11/13/2020, 12:43 AM
Agree about the second case, thanks!