Android Views in Jetpack Compose

75 Views Asked by At
var adRequested by remember { mutableStateOf(false) }

if (AdEventManager.isInternetAvailable() && !adRequested && 
        isNativeAdVisible && !App.isAppPremium) {

    AndroidViewBinding(
        NativeNoMediaCLayoutBinding::inflate,
        modifier = Modifier
            .fillMaxWidth()
            .weight(1f)
            .navigationBarsPadding()
    ) {
        App.mInstance?.adsManager?.loadNativeAd(
            context as Activity,
            adFrame,
            AdsManager.NativeAdType.NOMEDIA_MEDIUM,
            context.getString(R.string.ADMOB_NATIVE_WITHOUT_MEDIA_V2),
                              shimmerLayout)
    }

    adRequested = true
}

so here i want that when the ad is Loaded once then it should not be loaded again and again whenever the screen is recomposed so we go with a state that tracks that if the ad is loaded or not but the issue we have here is that even we cant make a side effect that will run this block only when its true.As by this code request is sent one time but when the screen recompose the ad is hidden as we have that in the if statement So how to make sure that the ad is loaded once and if was loaded then that View should remain same and don't reload

1

There are 1 best solutions below

1
Miroslav Hýbler On

Problem is that you are loading ad in update block which is used to update view during recomposition, from docs:

update - The callback to be invoked after the layout is inflated and upon recomposition to update the information and state of the binding

To solve this you have load ad in factory, i updated your code:

var adRequested by rememberSaveable { mutableStateOf(false) }

if (AdEventManager.isInternetAvailable() && !adRequested &&
isNativeAdVisible && !App.isAppPremium
) {
    AndroidViewBinding(
        factory = { binding, parent, attachToParent ->
            val binding =
                NativeNoMediaCLayoutBinding.inflate(binding, parent, attachToParent)

            App.mInstance?.adsManager?.loadNativeAd(
                context as Activity,
                binding.adFrame,
                AdsManager.NativeAdType.NOMEDIA_MEDIUM,
                context.getString(R.string.ADMOB_NATIVE_WITHOUT_MEDIA_V2),
                binding.shimmerLayout
            )
            adRequested = true
            binding
        },
        modifier = Modifier
            .fillMaxWidth()
            .weight(1f)
            .navigationBarsPadding()
    )
}