DEV Community

Cover image for Seen Is Not Rendered: Trustworthy Impression Tracking with Modifier.onVisibilityChanged
Android Expert
Android Expert

Posted on Originally published at Medium

Seen Is Not Rendered: Trustworthy Impression Tracking with Modifier.onVisibilityChanged

Somewhere in your analytics dashboard sits an impressions number that your product manager trusts more than it deserves. It drives ranking experiments, ad invoices, and “did the new card layout work?” debates. And on Android it is usually produced by a callback that fires when a composable happens to be laid out somewhere near the screen.

Compose 1.9 shipped first-class visibility modifiers, and the first one people reached for, onFirstVisible, is now deprecated. The reason is instructive: inside a LazyColumn it did not mean what its name promised. This post builds the replacement properly: a threshold-based, deduplicated, lifecycle-aware trackImpression() modifier, plus the failure modes that bite once the code meets real feeds, real users, and real analytics reviews.

Why onFirstVisible had to go

The documentation explains the deprecation plainly. A lazy list removes items from composition when they scroll away and composes them again when they return. Every time the node re-attaches, the “first” visibility starts over, so a callback named first visible ran again on each scroll-back. The recommended path is to use Modifier.onVisibilityChanged() and keep your own record of what has already been seen, based on what your use case actually needs.

That last clause is the important one. “Seen” is not a UI property; it is a product definition. The framework gives you geometry and time. You supply identity and scope.

Decide what an impression is before writing code

Write the definition down first. A defensible default, close to what ad-viewability conventions use for display content, is: at least 50% of the item inside the viewport for at least one continuous second, counted once per item per surface session.

That sentence contains four independent knobs, and each maps to a different mechanism:

  • Fraction → minFractionVisible
  • Dwell → minDurationMs
  • Identity → a stable item key you own
  • Scope → a ledger you can reset (refresh, new session, new query)

visibility-threshold

Two details deserve attention. First, the comparison is strictly greater than minFractionVisible, so with 0.5f an item that is exactly half visible does not qualify. Second, 1f does not demand that the whole rectangle fit inside the viewport. The API reference describes it as the entire bounds inside the viewport or the rect filling the viewport, and the implementation treats a fully visible node as visible whatever the threshold. An oversized hero card that fills a small split-screen window can therefore still produce an impression at 1f.

What I could not confirm from the documentation is how the fraction is computed for an item taller than the viewport at thresholds below 1f. Half of a 1,200 dp card is 600 dp, and a short window might never show that much of it. Pick thresholds per content type, and test oversized items in split-screen rather than assuming.

The API in thirty seconds

fun Modifier.onVisibilityChanged(
    minDurationMs: Long = 0,
    minFractionVisible: Float = 1f,
    viewportBounds: LayoutBoundsHolder? = null,
    callback: (visible: Boolean) -> Unit,
): Modifier
Enter fullscreen mode Exit fullscreen mode
  • callback(true) arrives once the visible fraction has been strictly above the threshold (or the node is fully visible) for the full duration.
  • callback(false) arrives when it stops qualifying. It is also sent when the node is detached, for example when a lazy item leaves composition, provided the last reported state was visible.
  • viewportBounds lets you replace "the window" with a rectangle you choose, which matters more than it first appears.

It is a layout-phase modifier, so it costs no extra composition and needs no LaunchedEffect per row. It also knows nothing about your product, your lists, or your lifecycle. Everything else in this post is the glue.

Five LazyList traps

lazylist-refire

1. Re-entry re-fires. Scroll an item out and back and callback(true) arrives again. If your handler logs directly, you now double-count every user who scrolls up to re-read something. Deduplicate on a key.

2. Missing item keys. Without key = { it.id }, lazy items are identified by index. Insert a card at the top and the same composition slot now hosts a different item. Always derive the impression key from your data id, never from position, and give the list the same key so state follows data.

3. Disposal wipes local state. A remember { mutableStateOf(false) } inside the row ("already reported") disappears when the row leaves composition. That is the original bug wearing a new costume. The record must live above the list: a ViewModel, a scoped holder, or an app-level singleton keyed by surface.

4. The viewport is not always the window. By default the check runs against the window. A top bar, bottom navigation bar, or any sibling that sits outside the list can still make the window a poor stand-in for what the user sees. Give the list Modifier.layoutBounds(holder) and pass the holder as viewportBounds, and the check runs against the list's own rectangle instead. Be precise about the limit: that rectangle excludes siblings outside the list, but it does not subtract something drawn on top of the list, such as a modal bottom sheet or a floating overlay. For overlays, suppress tracking yourself while they are showing (the tracker's foreground gate below is one place to hang that).

5. Prefetched items are not viewed items. Lazy lists compose items slightly ahead of the visible range. Geometry-based thresholds handle this naturally, because a prefetched item is not inside the viewport. That is one more reason to avoid hand-rolled “item composed means item seen” logic with LaunchedEffect(Unit), which counts every prefetch.

Debounce with dwell, not with Flow.debounce

It is tempting to collect snapshotFlow { listState.layoutInfo.visibleItemsInfo } and apply debounce. Resist it. Flow.debounce waits for a quiet period on a single stream. A user steadily scrolling through a feed never produces quiet, so you lose impressions precisely when engagement is highest. What you want is a per-item dwell timer, and that is what minDurationMs provides.

dwell-debounce

With minDurationMs = 500, a fling that drags a card through the viewport in 250 ms produces nothing. A card that stays gets callback(true) at the 500 ms mark and callback(false) when it leaves. Later Compose UI release notes list fixes to this exact bookkeeping, including delivering the false callback when a non-zero duration is configured and not calling back for a node that was never visible. The lesson: pin your Compose version and keep a test that exercises dwell behaviour, because this API has been evolving. The exact timing of the false callback has also shifted between versions, so the tracker below never relies on when it arrives, only that it eventually does. Community experiments have also reported missed callbacks under stress, so treat the modifier as a signal source and reconcile against a snapshot-based check in your own QA builds if the numbers matter financially.

Architecture

impression-pipeline

Each stage owns one responsibility, and each failure mode has exactly one place to be handled. The modifier measures; the ledger decides whether to count, and a session boundary (a successful refresh, a new query) decides when it forgets; the tracker decides how to ship.

Implementation

1. Model

import androidx.compose.runtime.Immutable

@JvmInline
value class SurfaceId(val value: String)

@Immutable
data class ImpressionKey(val surface: SurfaceId, val itemId: String)

@Immutable
data class ImpressionPolicy(
    val minFractionVisible: Float = 0.5f,
    val minDurationMs: Long = 1_000,
) {
    init {
        require(minFractionVisible in 0f..1f) { "fraction must be within 0..1" }
        require(minDurationMs >= 0) { "duration must not be negative" }
    }
}

data class ImpressionEvent(
    val key: ImpressionKey,
    val policy: ImpressionPolicy,
    val recordedAtElapsedMs: Long,
)

fun interface ImpressionSink {
    suspend fun deliver(batch: List<ImpressionEvent>)
}
Enter fullscreen mode Exit fullscreen mode

A value class for the surface keeps "home_feed" and "search_results" from being swapped with item ids. It is not free everywhere: the JVM boxes it when it is nullable, used as a generic type argument (a Map<SurfaceId, ...>, say) or typed as an interface. Here it only sits as a field, so the cost stays small.

2. A bounded ledger

class ImpressionLedger(private val capacity: Int = 2_000) {

    // Access-ordered LinkedHashMap used as an LRU set.
    private val seen =
        object : LinkedHashMap<ImpressionKey, Unit>(capacity.coerceAtLeast(16), 0.75f, true) {
            override fun removeEldestEntry(
                eldest: MutableMap.MutableEntry<ImpressionKey, Unit>?,
            ): Boolean = size > capacity
        }

    /** Returns true only the first time [key] is seen since the last reset. */
    fun markIfFirst(key: ImpressionKey): Boolean = seen.put(key, Unit) == null

    fun reset(surface: SurfaceId) {
        seen.keys.removeAll { it.surface == surface }
    }
}
Enter fullscreen mode Exit fullscreen mode

The bound matters. An endless feed with an unbounded HashSet is a slow memory leak that only shows up in long sessions. The trade-off of LRU eviction is that an item evicted from the ledger could be counted again if the user scrolls all the way back; at a capacity of a couple of thousand keys that is a conscious, documented approximation rather than a surprise. The ledger is main-thread confined by contract: every tracker entry point below is @MainThread. I could not find the visibility API documenting which thread its callback runs on, so treat that as an assumption to verify in your own app rather than a guarantee.

3. The tracker

The tracker holds two kinds of state: what has been counted (the ledger) and what is visible right now. The second is what lets it handle backgrounding correctly.

import android.os.SystemClock
import androidx.annotation.MainThread
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch

/**
 * [scope] must be bound to the main thread (viewModelScope is).
 * Every public function except [close] is main-thread only.
 */
class ImpressionTracker(
    private val ledger: ImpressionLedger,
    private val sink: ImpressionSink,
    private val scope: CoroutineScope,
    ioDispatcher: CoroutineDispatcher = Dispatchers.Default,
    private val elapsedRealtimeMs: () -> Long = SystemClock::elapsedRealtime,
    private val flushWindowMs: Long = 2_000,
    private val maxDeliveryAttempts: Int = 3,
    private val onDropped: (List<ImpressionEvent>, Throwable) -> Unit = { _, _ -> },
) {
    private val outbox = Channel<ImpressionEvent>(Channel.UNLIMITED)
    private val visibleNow = LinkedHashMap<ImpressionKey, ImpressionPolicy>()
    private val redwell = HashMap<ImpressionKey, Job>()
    private var foreground = false

    private val drainJob: Job = scope.launch(ioDispatcher) { drain() }

    /** The modifier reports a node that stayed above its threshold for its dwell time. */
    @MainThread
    fun onVisible(key: ImpressionKey, policy: ImpressionPolicy) {
        visibleNow[key] = policy
        redwell.remove(key)?.cancel() // a fresh callback supersedes any pending re-dwell
        if (foreground) record(key, policy)
    }

    /** The modifier reports the node stopped qualifying, or left composition. */
    @MainThread
    fun onHidden(key: ImpressionKey) {
        visibleNow.remove(key)
        redwell.remove(key)?.cancel()
    }

    /**
     * Called when the host goes to or leaves the started state. Items that stayed on screen
     * across a background trip fire no new visibility callback, so we re-check them here.
     */
    @MainThread
    fun setForeground(isForeground: Boolean) {
        foreground = isForeground
        if (!isForeground) {
            redwell.values.forEach(Job::cancel)
            redwell.clear()
            return
        }
        for ((key, policy) in visibleNow.entries.toList()) startRedwell(key, policy)
    }

    /** The user has to keep seeing the item for a full dwell before it counts again. */
    private fun startRedwell(key: ImpressionKey, policy: ImpressionPolicy) {
        if (key in redwell) return
        redwell[key] = scope.launch {
            delay(policy.minDurationMs)
            redwell.remove(key)
            if (foreground && key in visibleNow) record(key, policy)
        }
    }

    /**
     * Starts a new exposure session for [surface]. Items still on screen fire no new
     * visibility callback, so they are re-checked with a fresh dwell, as after a background trip.
     */
    @MainThread
    fun resetSurface(surface: SurfaceId) {
        ledger.reset(surface)
        if (!foreground) return // setForeground(true) will re-check them
        for ((key, policy) in visibleNow.entries.toList()) {
            if (key.surface == surface) startRedwell(key, policy)
        }
    }

    fun close() {
        outbox.close()
        drainJob.cancel() // also interrupts a flush delay or a retry backoff in flight
    }

    private fun record(key: ImpressionKey, policy: ImpressionPolicy) {
        if (!ledger.markIfFirst(key)) return
        outbox.trySend(ImpressionEvent(key, policy, elapsedRealtimeMs()))
    }

    private suspend fun drain() {
        for (first in outbox) {
            delay(flushWindowMs) // let a burst accumulate into one batch
            val batch = mutableListOf(first)
            while (true) batch += outbox.tryReceive().getOrNull() ?: break
            deliverWithRetry(batch)
        }
    }

    private suspend fun deliverWithRetry(batch: List<ImpressionEvent>) {
        var attempt = 0
        while (true) {
            try {
                sink.deliver(batch)
                return
            } catch (e: CancellationException) {
                throw e
            } catch (e: Exception) {
                if (++attempt >= maxDeliveryAttempts) {
                    onDropped(batch, e) // hand off to disk or a metric; never retry forever
                    return
                }
                delay(flushWindowMs * (1L shl attempt)) // exponential backoff
            }
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Three decisions are worth defending.

Unbounded channel, bounded input. The ledger caps the event rate at one event per unique key per surface session, so the queue cannot grow faster than the content the user actually saw.

Bounded retries. A failing sink used to mean an endless re-queue loop. Now a batch is retried with exponential backoff up to maxDeliveryAttempts, then handed to onDropped, which is where a production build would spill to disk or bump a counter.

At-most-once, on purpose. A key is marked in the ledger before delivery succeeds, so a process death mid-flush loses that batch. If the business cannot accept that, persist the outbox. Also call close() when the tracker's owner goes away if the scope can outlive it; with viewModelScope the drain loop is cancelled for you. Note that close() cancels the drain job immediately, so events still queued or mid-retry are dropped; if you need a final flush, deliver the remaining batch yourself before closing.

4. The modifier

import androidx.compose.ui.Modifier
import androidx.compose.ui.layout.LayoutBoundsHolder
import androidx.compose.ui.layout.onVisibilityChanged

fun Modifier.trackImpression(
    tracker: ImpressionTracker,
    key: ImpressionKey,
    policy: ImpressionPolicy = ImpressionPolicy(),
    viewportBounds: LayoutBoundsHolder? = null,
): Modifier = onVisibilityChanged(
    minDurationMs = policy.minDurationMs,
    minFractionVisible = policy.minFractionVisible,
    viewportBounds = viewportBounds,
) { visible ->
    if (visible) tracker.onVisible(key, policy) else tracker.onHidden(key)
}
Enter fullscreen mode Exit fullscreen mode

This is a plain modifier factory, not a @Composable one. Compose's modifier guidelines discourage composable factories (there is lint for it), because a composable modifier must be re-evaluated inside composition and cannot be created once and reused. The tracker is an explicit parameter instead of a CompositionLocal read inside the factory. If you prefer a local, read it once at the screen level and pass it down.

The modifier no longer checks the lifecycle itself. Doing so inside the callback was a real bug: the check runs only at the instant visible flips, and an item that stays on screen while the app is stopped and restarted gets no new callback, so its impression would be lost for good. The foreground state now lives in the tracker, fed by one small effect:

import androidx.compose.runtime.Composable
import androidx.lifecycle.compose.LifecycleStartEffect

@Composable
fun TrackForeground(tracker: ImpressionTracker) {
    LifecycleStartEffect(tracker) {
        tracker.setForeground(true)
        onStopOrDispose { tracker.setForeground(false) }
    }
}
Enter fullscreen mode Exit fullscreen mode

STARTED rather than RESUMED stays deliberate: a visible but unfocused window in split-screen is still in front of the user.

Wiring it up

FeedRepository, FeedItem (with an id and a kind) and FeedCard below are your own types; the snippet shows only the tracking-relevant parts.

import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import androidx.compose.ui.layout.LayoutBoundsHolder
import androidx.compose.ui.layout.layoutBounds
import androidx.lifecycle.ViewModel
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.Job
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.launch

private val FeedSurface = SurfaceId("home_feed")

class FeedViewModel(
    private val repository: FeedRepository,
    sink: ImpressionSink,
) : ViewModel() {

    // Lives as long as the screen's state, so rotation and back-navigation do not recount.
    val impressions = ImpressionTracker(ImpressionLedger(), sink, viewModelScope)

    private val _items = MutableStateFlow<List<FeedItem>>(emptyList())
    val items: StateFlow<List<FeedItem>> = _items.asStateFlow()

    private var refreshJob: Job? = null

    fun onPullToRefresh() {
        refreshJob?.cancel() // a newer pull supersedes an older one
        refreshJob = viewModelScope.launch {
            val fresh = try {
                repository.loadFeed()
            } catch (e: CancellationException) {
                throw e
            } catch (e: Exception) {
                // Keep the old items AND the old ledger: the user is still looking
                // at the same cards. Surface the error in your UI state here.
                return@launch
            }
            // No suspension point between these two lines, so no visibility callback
            // can land between the reset and the swap. Reset only once the data is accepted.
            impressions.resetSurface(FeedSurface)
            _items.value = fresh
        }
    }
}

@Composable
fun FeedScreen(viewModel: FeedViewModel) {
    val items by viewModel.items.collectAsStateWithLifecycle()
    val viewport = remember { LayoutBoundsHolder() }

    TrackForeground(viewModel.impressions)

    LazyColumn(Modifier.layoutBounds(viewport)) {
        items(items, key = { it.id }, contentType = { it.kind }) { item ->
            FeedCard(
                item = item,
                modifier = Modifier.trackImpression(
                    tracker = viewModel.impressions,
                    key = ImpressionKey(FeedSurface, item.id),
                    viewportBounds = viewport,
                ),
            )
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Note where the reset happens. A pull gesture is not a new exposure session; accepting new data is. If the load fails, the old cards stay on screen and the old ledger stays with them. The reset and the item swap run back to back with no suspension between them, so no frame can show new items against the old ledger or old items against a cleared one. Cancelling the previous refreshJob stops a slow, older response from resetting the ledger after a newer one has been accepted.

Test the part that can be tested

The ledger and tracker are plain Kotlin, so test them in virtual time instead of waiting on a device. The second test covers the lifecycle bug that the first version of this design had, and the third covers the refresh boundary: a reset while an item never left the screen.

import kotlin.test.assertEquals
import kotlin.test.assertTrue
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.test.StandardTestDispatcher
import kotlinx.coroutines.test.TestScope
import kotlinx.coroutines.test.advanceTimeBy
import kotlinx.coroutines.test.runCurrent
import kotlinx.coroutines.test.runTest
import org.junit.Test

class RecordingSink : ImpressionSink {
    val delivered = mutableListOf<ImpressionEvent>()
    override suspend fun deliver(batch: List<ImpressionEvent>) {
        delivered += batch
    }
}

@OptIn(ExperimentalCoroutinesApi::class)
class ImpressionTrackerTest {

    private fun TestScope.newTracker(sink: ImpressionSink) = ImpressionTracker(
        ledger = ImpressionLedger(),
        sink = sink,
        scope = backgroundScope,
        ioDispatcher = StandardTestDispatcher(testScheduler),
        elapsedRealtimeMs = { testScheduler.currentTime },
        flushWindowMs = 10,
    )

    private val key = ImpressionKey(SurfaceId("feed"), "card-42")

    @Test
    fun `scrolling back does not record a second impression`() = runTest {
        val sink = RecordingSink()
        val tracker = newTracker(sink)
        tracker.setForeground(true)

        tracker.onVisible(key, ImpressionPolicy())
        tracker.onHidden(key)
        tracker.onVisible(key, ImpressionPolicy()) // the scroll-back
        advanceTimeBy(11)
        runCurrent()

        assertEquals(listOf(key), sink.delivered.map { it.key })
    }

    @Test
    fun `item that stays visible across a background trip counts after a fresh dwell`() = runTest {
        val sink = RecordingSink()
        val tracker = newTracker(sink)
        val policy = ImpressionPolicy(minDurationMs = 1_000)

        tracker.onVisible(key, policy) // dwell finished while the app was stopped
        advanceTimeBy(5_000)
        runCurrent()
        assertTrue(sink.delivered.isEmpty())

        tracker.setForeground(true)
        advanceTimeBy(999)
        runCurrent()
        assertTrue(sink.delivered.isEmpty()) // not yet: the dwell restarts on return

        advanceTimeBy(100)
        runCurrent()
        assertEquals(listOf(key), sink.delivered.map { it.key })
    }

    @Test
    fun `reset while an item stays on screen re-counts it after a fresh dwell`() = runTest {
        val sink = RecordingSink()
        val tracker = newTracker(sink)
        val policy = ImpressionPolicy(minDurationMs = 1_000)
        tracker.setForeground(true)

        tracker.onVisible(key, policy)
        advanceTimeBy(20)
        runCurrent()
        assertEquals(1, sink.delivered.size)

        tracker.resetSurface(key.surface) // successful refresh, item never left the screen
        advanceTimeBy(999)
        runCurrent()
        assertEquals(1, sink.delivered.size) // dwell has not elapsed yet

        advanceTimeBy(100)
        runCurrent()
        assertEquals(2, sink.delivered.size)
    }
}
Enter fullscreen mode Exit fullscreen mode

Add a FeedViewModel test with a fake repository covering the other half: a loadFeed() that throws must leave the ledger untouched (scroll-back still produces one event), and a successful load must clear it. For the modifier itself, use a Compose UI test that scrolls a list with mainClock.autoAdvance = false, advances the clock past minDurationMs, and asserts on a recording sink. Keep that test on the exact Compose version you ship.

Field notes: failures you will meet in production

  • Refresh semantics. If the ledger is never reset, a refreshed feed full of repeated items under-counts. If it resets on every recomposition, you over-count. If it resets when the pull gesture starts, a failed refresh double-counts the unchanged cards. Tie resetSurface to the moment new data is accepted, not to the gesture that requested it, and cancel superseded refreshes so a stale response cannot reset the ledger late. Whether a refresh that returns identical content counts as a new session is a product decision; write it down.
  • Process death. A ViewModel ledger survives rotation, not process death. After a restore the user may be credited with the same items again. Decide whether that is acceptable or persist the ledger.
  • Multi-window and PiP. STARTED is deliberately used instead of RESUMED, because a visible but unfocused window in split-screen is still seen by the user.
  • Overlays. A bottom sheet or floating panel drawn over the list is not subtracted by layoutBounds. Pause tracking while it is up, or accept the over-count.
  • Oversized or tiny items. Fractions behave differently for a 60 dp row and a 900 dp banner. Use a per-content-type ImpressionPolicy.
  • Version drift. This API changed between releases. Re-run your dwell test on every Compose bump, and compare against a server-side or snapshot-based count in internal builds.
  • Ad billing. If money depends on the number, validate against the ad network’s own viewability definition. Your 50%/1s rule is a default, not a contract.

Choosing an approach

approach-comparison

Using onVisibilityChanged alone gives you correct geometry and dwell but not correct counting. The ledger is what turns a visibility signal into an impression.

Pre-ship checklist

  • The impression definition (fraction, dwell, scope) is written down and agreed with analytics.
  • Lists use stable keys and the impression key comes from data ids.
  • The “already seen” record lives outside the lazy item.
  • The ledger is reset when refreshed data is accepted, never when a refresh is merely requested, and a failed refresh keeps the old ledger.
  • viewportBounds is set whenever bars or headers sit around the list, and overlays drawn over the list are handled separately.
  • The tracker is told about foreground and background, so an item that never left the screen still counts on return.
  • Delivery semantics (at-most-once vs at-least-once) are chosen on purpose.
  • A virtual-time test covers dedupe and reset; a UI test covers dwell on your pinned Compose version.

🧵 Stop Treating Coroutines Like Magic Keywords

If “just add launch and hope” describes how your team handles concurrency, I’d recommend “Kotlin Coroutines Under the Hood” — a 25-chapter deep dive that goes past the syntax and down to the bytecode: the Continuation-Passing Style transform, the compiler-generated state machine, and exactly why a suspended coroutine costs a few dozen bytes while a blocked thread costs a megabyte.

It walks through structured concurrency and Job hierarchies, dispatcher internals (Default vs IO vs Unconfined), cooperative cancellation and exception aggregation, Flow’s cold-stream semantics and the full operator vocabulary, StateFlow/SharedFlow’s hot-broadcast model, Channels and fan-in/fan-out patterns, Mutex/Semaphore/actors for shared state, and a complete Android case study retrofitting a legacy callback-driven app onto coroutines and Flow — including a 100,000-coroutines-vs-100,000-threads benchmark lab you can run yourself.

Top comments (0)