Is it possible to enable a composable to reload itself without composition occuring

106 Views Asked by At

I have recently started to transition to using compose from xml. I am using compose in conjunction with fragment views. I have used android view to wrap around an AdView that is supposed to show ads in my app. Currently, I am using two instances of the AdView in the same screen, one is just below the app bar and one is within a lazy column. The lazy column would be updated with new data change each time I switch to a different date filters (for example tomorrow, yesterday etc) and the view remains in the same fragment. The AdView instance within the lazy column is re rendering each time which is expected. However, the AdView below the app bar never re render unless i am navigating to and back from a another fragment. Is it possible to enable the app bar adview to re render itself each time I update another component in the same screen.

This is the code for the AdView. Thank you

@Composable
fun ComposeAds(
    adSection: AdSection,
    adSize: AdSize,
    modifier: Modifier = Modifier,
) {

    AndroidView(modifier = modifier
        .fillMaxWidth()
        .background(MaterialTheme.colorScheme.background)
        .padding(vertical = 8.dp),
        factory = { context ->
            val adView = AdManagerAdView(context)
            adView.loadPublisherAd(adSection, adSize)
            /* after the ads have loaded we request layout since some ads sizes are not
             the standard sizes the adView is expecting */
            adView.adListener = object : AdListener() {
                override fun onAdLoaded() {
                    super.onAdLoaded()
                    adView.rootView.requestLayout()
                }
            }
            adView
        },
        onReset = {
        /* we have a non- null onReset to signal this view
           is about to be reused, refer to the link be below for more info
     https://developer.android.com/jetpack/compose/migrate/interoperability-apis/views-in-compose */
        }
    )
}

I tried using MutableStateOf with a boolean and each time i switch a date filter then set the boolean to true to signal the view to re render itself. However i am struggling with the implementation logic

1

There are 1 best solutions below

0
Roman Y On

Seems you want to force a new AndroidView each time filter was changed? If so, try wrap the AndroidView with key.

key(filterState.value) {
    AndroidView(....)
}

https://developer.android.com/reference/kotlin/androidx/compose/runtime/package-summary#key(kotlin.Array,kotlin.Function0)