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.
CodePudding user response:
factory
is getting called only once, when the view is created. That's why the lambda captures only the initial state.
To pass an updated state, you need to use update
argument, like this:
AndroidView(
modifier = modifier,
factory = { context ->
ScannerView(context)
},
update = { view
view.onButtonClicked = {
if (state.isLoading) {
...
}
}
},
)