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

Mao

11/03/2020, 9:17 AM
Hi. I have a question about how to choose
ambientOf
and
staticAmbientOf
. Since
staticAmbientOf
will force all children doing recomposition, seems like
ambientOf
is more efficient. But after search the source code, I found that there are more occurrences of
staticAmbientOf
. I understand that most of them are rarely changed and the comment of
staticAmbientOf
says:
Copy code
A static ambient should be only be used when the value provided is highly unlikely to change.
But why not just using
staticOf
? Are there any circumstances that we must do all children recomposition? I would be very happy if there were some guides to told me how to choose between
ambientOf
and
staticAmbientOf
. Thanks!
j

jim

11/03/2020, 1:06 PM
If
ambientOf
were purely more efficient, we wouldn't even provide
staticAmbientOf
. But it's not true, the costs are just different. As you mentioned,
staticAmbientOf
will force a recomposition of all children, which means you pay the cost (and may drop frame) when you change the ambient, but it is cheaper to setup because you aren't setting up large numbers of subscriptions on every usage of the ambient.
ambientOf
in contrast does more targeted updates, which can make recomposition faster, but you pay the cost when building/maintaining the initial tree, making your whole app slower even in cases where the ambient never changes. Both have pros and cons, but static ambients are probably more common because most things which are ambient values should be consumed by large numbers of nodes (otherwise, you should be passing them as parameters) and things that are consumed by large numbers of nodes empirically seem to change not very often (eg. user's preferred language).
👍 1
m

Mao

11/03/2020, 2:04 PM
Thanks for your response!
but you pay the cost when building/maintaining the initial tree
I haven’t thought of the cost of using
State
(wrapped by the
ambientOf
) and didn’t notice that resolving a lot of dependencies for a
State
can take much time. So the principle of choosing
staticAmbientOf
and
ambientOf
basically depends on whether we need to do more reading or writing, right?
j

jim

11/03/2020, 3:55 PM
yes
❤️ 1