https://kotlinlang.org logo
Title
m

Manuel Unterhofer

05/08/2023, 7:39 AM
What’s the canonical way of automatically giving focus to an element that enters the composition within the same frame? I saw several examples online that suggest using a
FocusRequester
within a
LaunchedEffect
but I am worried that this would not reliably happen within the same frame because the coroutine behind
LaunchedEffect
might be scheduled too late?
l

Loney Chou

05/08/2023, 8:46 AM
May I ask what frame are you referring to? Like, same frame with what.
Anyway, the only way to manually request focus on a specific component is by using
FocusRequester
+
Modifier.focusRequester
or
FocusRequesterModifierNode
(experimental), and most of the time you would use the former. A FocusRequester needs to know where it is in order to search for a focusable target, and this is done during the composition phase (when updating the
modifier
of a
LayoutNode
). Considering not causing any weird issue, using
XxxEffect
should be the safest and fastest way, because they get executed right after the composition is ready (if I remember correctly).
You may use
DisposableEffect
for it right. It gets executed on the spot, unlike
LaunchedEffect
which will somehow "schedule" the execution, it depends.
m

Manuel Unterhofer

05/08/2023, 9:25 AM
Frame as in update of the UI, one update cycle that the user will see.
Ah, I forgot that
DisposableEffect
has keys. That should solve it, thanks!
z

Zach Klippenstein (he/him) [MOD]

05/15/2023, 11:19 PM
LaunchedEffect
should work as well. The coroutines are scheduled at the same time as `DisposableEffect`s are ran, and so they will always be dispatched before the next frame’s input handling phase (which is the first thing the choreographer does)