Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why state update not reflected on AndroidView

In Jetpack Compose, I have an AndroidView with a listener that reads the state passed like this:

@Composable
fun Scanner(
    state: ScannerState,
    modifier: Modifier = Modifier,
) {
    AndroidView(
        modifier = modifier,
        factory = { context ->
            ScannerView(context).apply {
                onButtonClicked = {
                    if (state.isLoading) <-- HERE I READ THE STATE   
                        ...
                    }
                }
            }
        },

The problem comes when the state is updated and the view recomposed. If the onButtonClicked callback is invoked again after that, it holds the initial state, and it's not reading the last updated state that this function received.

like image 722
Victor Manuel Pineda Murcia Avatar asked Aug 02 '26 09:08

Victor Manuel Pineda Murcia


1 Answers

factory is getting called only once, when the view is created. That's why the lambda captures only the initial state.

To pass the updated state, you need to use update argument, like this:

AndroidView(
    modifier = modifier,
    factory = { context ->
        ScannerView(context)
    },
    update = { view 
        view.onButtonClicked = {
            if (state.isLoading) {
                ...
            }
        }
    },
)
like image 153
Philip Dukhov Avatar answered Aug 07 '26 00:08

Philip Dukhov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!