Skip to content
This repository has been archived by the owner on Sep 27, 2024. It is now read-only.

Composable AndroidView update block is run on every key press #856

Closed
jonnyandrew opened this issue Oct 25, 2023 · 4 comments · Fixed by #866
Closed

Composable AndroidView update block is run on every key press #856

jonnyandrew opened this issue Oct 25, 2023 · 4 comments · Fixed by #866

Comments

@jonnyandrew
Copy link
Contributor

jonnyandrew commented Oct 25, 2023

Problem

The update block of the composable AndroidView is run on every key press, whereas it should only run when a variable used inside the block is changed.

This block is supposed to run any time the style or callbacks are changed and isn't optimised to be run very frequently.

Proposed solution

Workaround implemented in #854

No solution is known.

@jonnyandrew jonnyandrew changed the title Compose AndroidView update block is run on every key press Composable AndroidView update block is run on every key press Oct 25, 2023
@jmartinesp
Copy link
Contributor

I think this is actually working as expected (although we didn't expect it to work like that 😅 ): looking at the source code, we can see the update lambda will only be called when the lambda instance changes, and this can happen in 2 scenarios:

  1. Any variable captured in the lambda changes.
  2. A recomposition of the parent composable.

By using a remember block we can cache the lambda using some keys (in this case, the captured arguments) and reuse it even if the parent composable is recomposed, instead of getting a new lamda.

As for why there were different behaviours after a clean build and an incremental one, I have no idea. It might be a compiler bug.

@jonnyandrew
Copy link
Contributor Author

the update lambda will be called on a recomposition of the parent composable.

I thought the update block should only run again when one of the variables inside it changes, not whenever the parent recomposes. I created a small sample to test it and it seems to be working in this way. Can you let me know if I misunderstood something here?

@jmartinesp
Copy link
Contributor

My theory was the AndroidView would be recomposed when anything captured in the onFactory lambda changed too, and this would in turn recompose the update lambda, but that wasn't the case after some quick testing, so it seems like I was wrong.

@jonnyandrew
Copy link
Contributor Author

With Android Studio Hedgehog we're able to debug the reasons for recomposition and it looks to be caused by the onError passed from the sample app:

The only difference seems to be that we're passing a function reference. Replacing it with a lambda seems to make the issue go away but I have no idea why.

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Projects
None yet
2 participants