2

In Jetpack Compose I'm using AndroidView to display an ad banner from a company called Smart.IO.

At the moment the banner shows when first initialised, but then fails to recompose when user comes back to the screen it's displayed on.

I'm aware of using the update function inside compose view, but I can't find any parameters I could use to essentially update on Banner to trigger the recomposition.

AndroidView(
    modifier = Modifier
        .fillMaxWidth(),
    factory = { context ->
        Banner(context as Activity?)
    },
    update = {
        
    }
)
Phil Dukhov
  • 67,741
  • 15
  • 184
  • 220
alfietap
  • 1,585
  • 1
  • 15
  • 38

1 Answers1

3

This could be a library error. You can check if this view behaves normally in normal Android XML.

Or maybe you need to use some API from this library, personally I haven't found any decent documentation or Android SDK source code.


Anyway, here is how you can make your view update.

You can keep track of life-cycle events, as shown in this answer, and only display your view during ON_RESUME. This will take it off the screen when it is paused, and make it create a new view when it resumes:

val lifeCycleState by LocalLifecycleOwner.current.lifecycle.observeAsSate()
if (lifeCycleState == Lifecycle.Event.ON_RESUME) {
    AndroidView(
        modifier = Modifier
            .fillMaxWidth(),
        factory = { context ->
            Banner(context as Activity?)
        },
        update = {

        }
    )
}

Lifecycle.observeAsSate:

@Composable
fun Lifecycle.observeAsSate(): State<Lifecycle.Event> {
    val state = remember { mutableStateOf(Lifecycle.Event.ON_ANY) }
    DisposableEffect(this) {
        val observer = LifecycleEventObserver { _, event ->
            state.value = event
        }
        this@observeAsSate.addObserver(observer)
        onDispose {
            this@observeAsSate.removeObserver(observer)
        }
    }
    return state
}
Phil Dukhov
  • 67,741
  • 15
  • 184
  • 220
  • Thank you for the sample, I can see this makes the composable area recompose as it pushes my other composable down on the screen, but the actual data inside the banner doesn't load. The data does load however if i trigger an alert dialog on the screen which is odd. – alfietap Oct 27 '21 at 08:18
  • @alfietap You can put some empty `Box` of the same size in `else` to prevent this jump. As for the underlying problem, you probably need to contact SDK support, since you're doing everything right in the Compose part. – Phil Dukhov Oct 27 '21 at 08:25