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

Ahmet Delibaş

01/20/2021, 1:53 PM
I have a state
Copy code
var current by remember { mutableStateOf(0) }
after any change on current value, AndroidView component does not recompose. Does anybody know the answer? How can I update the AndroidView() part?
a

Adam Powell

01/20/2021, 3:07 PM
Can you post some more of the affected code that isn't behaving the way you expect?
a

Ahmet Delibaş

01/21/2021, 6:10 AM
Copy code
@Composable
fun StoryCaptureScreen(
    backAction: () -> Unit,
    modifier: Modifier,
) {
    var currentCam by remember { mutableStateOf(0) }

    val switchAction = { currentCam = switchCamera(currentCam) }

    Box(modifier = modifier.fillMaxSize()) {
        StoryCamera(currentCam)
        StoryCaptureOverlayUI(backAction, modifier, switchAction)
    }
}
Copy code
@Composable
fun StoryCamera(currentCam: Int) {
    val lifecycleOwner = AmbientLifecycleOwner.current
    val context = AmbientContext.current
    val cameraProviderFuture =  ProcessCameraProvider.getInstance(context)
    
    AndroidView(
        viewBlock = {
            PreviewView(context).apply {
            cameraProviderFuture.addListener({
                val cameraProvider = cameraProviderFuture.get()
                bindPreview(
                    lifecycleOwner,
                    this,
                    cameraProvider,
                    currentCam
                )
            }, ContextCompat.getMainExecutor(context)
            )
            scaleType = PreviewView.ScaleType.FILL_CENTER
        } },
        modifier = Modifier.fillMaxSize(),
    )
}
in uı there is switch button. If I click, then currentCam value changes.
Then recompose process starts. But AndroidView is not recomposed. I logged the code, last stop is cameraProviderFuture, just before the AndroidView.
a

Adam Powell

01/21/2021, 6:17 AM
from `AndroidView`'s docs: "The [viewBlock] block will be called exactly once to obtain the [View] to be composed" - that construction block never recomposes. You need to use the trailing lambda update block to apply changes from recomposition.
a

Ahmet Delibaş

01/21/2021, 6:28 AM
Yes I read the document. But in the document it says:
Copy code
AndroidView({ customView }) { view ->
        // View's been inflated - add logic here if necessary

        // As selectedItem is read here, AndroidView will recompose
        // whenever the state changes
        // Example of Compose -> View communication
        view.coordinator.selectedItem = selectedItem.value
    }
https://developer.android.com/jetpack/compose/interop#views-in-compose
BUt I cannot use coordinator ? There is no object like coordinator in view.
I found the answer. So thanks.
9 Views