NativeAdCache

Keeps the native ads of one screen alive while their slots scroll in and out of view.

A lazy list or grid disposes an item as soon as it leaves the viewport. An uncached slot destroys its ad with it, so every scroll back sends a new request, shows an empty cell until it returns, and lowers the match rate the network reports for the unit. A slot given this cache and a key leaves its ad here on disposal and takes the same ad back the next time it is composed.

Create one per screen with rememberNativeAdCache, outside the lazy layout, and pass it with a key to NativeAdSlot, rememberNativeAd, or rememberNativeAdState:

val adCache = rememberNativeAdCache()
LazyColumn {
items(items, key = { it.key }) { item ->
if (item is Row.Ad) {
NativeAdSlot(
adUnitId = adUnitId,
presentation = NativeAdPresentation.Card,
cache = adCache,
cacheKey = item.key,
)
}
}
}

The rules:

  • A key must belong to one slot at a time. Two slots composed together under the same key would bind one ad to two views, which the SDK does not allow. The item's lazy-layout key fits well.

  • A request still in flight when its slot scrolls away finishes into the cache.

  • A slot that came back empty is not remembered, so it asks again the next time it is composed.

  • An ad older than maxAdAge is replaced the next time its slot is composed, because the SDK asks for native ads to be shown within an hour of loading.

  • Every ad is destroyed when the cache leaves composition. A configuration change therefore requests again; a NativeAd holds views and cannot outlive the activity.

Types

Link copied to clipboard
object Companion