Contents
CWCoding With DhrumilCW Practical Flutter and Kotlin tutorials for working mobile developers

Home › Articles

Kotlin Coroutines on Android: Mistakes and Fix Numbers

By Priya Shah · Published · 5 min read

Tangled threads and ropes close-up representing concurrency mistakes in coroutines.
Tangled threads and ropes close-up representing concurrency mistakes in coroutines. · Foto: igorovsyannykov / Pixabay

Coroutines make async Android code read like synchronous code, which is exactly why mistakes hide so well. A blocked main thread, a job that outlives its screen, or a request with no timeout all look fine in review and only show up as jank, leaked memory or a frozen UI in production.

This article walks through the mistakes I see most often, with concrete dispatcher choices, timeout ranges and cancellation patterns you can apply today. No theory dumps, just the numbers and habits that keep coroutine code predictable.

Picking the Wrong Dispatcher for the Work

The default for launch in a ViewModel scope is Dispatchers.Main.immediate, which is right for touching UI state and wrong for anything that takes longer than a frame. At 60 Hz you have roughly 16 ms per frame, and at 120 Hz about 8 ms, so a database read or JSON parse on the main thread shows up as visible jank almost instantly.

The rule I follow: suspend functions that do I/O declare withContext(Dispatchers.IO) internally and callers never worry about it. Dispatchers.IO scales up to 64 threads by default (the system property kotlinx.coroutines.io.parallelism), so it handles many parallel network or disk calls, but it is not a CPU pool.

For parsing, sorting and image maths use Dispatchers.Default, which is sized to the number of CPU cores. On a typical 8-core phone that means 8 concurrent workers, so heavy parallel work beyond that just queues. Default is also the right place for CPU-heavy operators like sortedBy on large lists.

Avoid Dispatchers.Unconfined outside of tests and very specific callback bridging. It resumes on whatever thread completed the previous operation, which makes thread assumptions unpredictable and is the fastest route to an IllegalStateException from a UI update off the main thread.

  • UI state updates: Dispatchers.Main.immediate
  • Network, file and database calls: Dispatchers.IO
  • Parsing, sorting, hashing: Dispatchers.Default
  • Never guess: declare the dispatcher inside the suspend function

No Timeouts, No Retries, No Ceiling

A network call with no timeout can hang for minutes on a flaky mobile connection, and the user sees a spinner until they kill the app. Wrap the call in withTimeout: 10 to 15 seconds is a sensible ceiling for most API requests, 5 to 8 seconds for small metadata calls, and 30 seconds or more only for uploads and downloads.

withTimeout throws TimeoutCancellationException, which is a CancellationException subclass, so a generic catch (e: Exception) block will swallow it and your UI will show a failure as success. Catch it explicitly, or catch only the exceptions you expect and let cancellation propagate.

Retries deserve the same care. Two or three attempts with exponential backoff starting around 500 ms and capped near 5 to 10 seconds handles transient failures without hammering a struggling server. Retry only idempotent calls; retrying a payment POST three times is how duplicate charges happen.

Also remember that withTimeout cancels cooperatively. A blocking JDBC call or a tight loop with no suspension point ignores the timeout entirely, so the ceiling only works if the code inside actually suspends or checks for cancellation.

Leaking Scopes and Jobs

GlobalScope.launch is the classic leak: the coroutine keeps running after the Activity is destroyed, holds a reference to the view, and can crash when it tries to update it. Use lifecycleScope in Activities and Fragments, viewModelScope in ViewModels, and repeatOnLifecycle(STARTED) for flows collected from the UI.

In a ViewModel, a request started in init keeps running after the user leaves the screen. If the screen is gone for good, that work is wasted bandwidth and battery. Storing the Job and cancelling it when the user navigates away, or using a state-driven approach, saves real resources on a phone with limited data.

structured concurrency is your friend: a coroutine launched inside another is cancelled when the parent is cancelled. If you create a scope manually, always tie it to a lifecycle owner with CoroutineScope(SupervisorJob() + Dispatchers.Main) and cancel it in onDestroy, or better, avoid manual scopes entirely.

One quick check I run before merging: search for GlobalScope, runBlocking and CoroutineScope( in the diff. Each one is either a deliberate decision with a comment or a bug waiting for a slow network to expose it.

Recommended coroutine settings by task type
TaskDispatcherTimeoutRetryNotes
Small metadata API callIO5-8 s2 tries, 500 ms backoffIdempotent GET only
Main API requestIO10-15 s2-3 tries, cap 5-10 sRethrow CancellationException
File or database readIONo timeout, cancellableNoneCheck ensureActive() in loops
JSON parse, sortingDefaultN/ANoneKeep under 16 ms per frame chunk
Image processingDefaultN/ANoneParallelism equals CPU cores
Search inputDefault + flow10 s per requestNoneDebounce 250-400 ms, flatMapLatest

Ignoring Cancellation and Swallowing Exceptions

Cooperative cancellation means suspend functions must check. A loop that processes 10,000 items should call ensureActive() or yield() every few hundred iterations, otherwise cancelling the job does nothing until the loop ends. Similarly, delay() is cancellable but Thread.sleep() is not.

Catching CancellationException is the most damaging exception mistake. Code like catch (e: Exception) around a network call catches cancellation, logs it as an error and continues, so the coroutine outlives its scope and the UI updates after the screen is gone. Always rethrow CancellationException or use the specific exception types.

For fire-and-forget work in viewModelScope, add a CoroutineExceptionHandler or wrap the body in try/catch and report failures to a state object. An uncaught exception in a launched coroutine crashes the app by default, so a missing catch turns a recoverable API error into a crash report.

Finally, prefer async/await over many independent launch calls when you need results. Running three parallel requests with async usually finishes in the time of the slowest one (say 300 to 600 ms) instead of the sum, and await gives you a single place to handle errors.

250Metadata GET600API request40DB read25JSON parse300Debounce window
Typical coroutine task duration on Android (ms) (ms)

Flows and Shared State Done Carelessly

Collecting a StateFlow in an Activity with lifecycleScope.launch { flow.collect { } } keeps collecting while the app is in the background, wasting work and potentially updating invisible UI. Use repeatOnLifecycle(Lifecycle.State.STARTED) or the flowWithLifecycle operator so collection pauses below STARTED and resumes automatically.

On the producer side, stateIn with SharingStarted.WhileSubscribed(5000) is a good default for UI state. The 5-second grace period survives a quick rotation without restarting the upstream flow, while still stopping work a few seconds after the user leaves. Tune it between 0 and 5,000 ms depending on how expensive the source is.

For debouncing search input, 250 to 400 ms is the usual sweet spot: fast enough to feel responsive, slow enough to skip most intermediate keystrokes. Combine it with flatMapLatest so an in-flight request is cancelled when the query changes, and you avoid out-of-order results from slower earlier calls.

Testing and Measuring the Result

Tests are where dispatcher mistakes become obvious. Inject a dispatcher instead of hardcoding Dispatchers.IO, and in tests replace it with a StandardTestDispatcher plus runTest. Virtual time means a 10-second delay completes instantly and, more importantly, every timeout and retry path becomes testable without real waiting.

Measure before you optimise. A few numbers worth tracking: main-thread block time per frame (keep under 8 to 16 ms), the number of active coroutines during a screen's lifetime (should drop to near zero on exit), and crash-free sessions after adding timeouts and exception handling.

If you build UI with Flutter rather than Compose or Views, the same discipline applies to async work and timing Flutter Animation Controllers Explained With Timing Numbers, and the widget choice discussion in Cupertino vs Material Widgets: Which Style Fits Your App? pairs well with a state-first architecture.

A Short Checklist Before You Ship

Coroutine code goes wrong quietly, so a checklist beats memory. Most production issues I have seen trace back to a dispatcher assumption, a missing timeout, or a scope that outlived its owner, and all three are cheap to catch in review.

For list-heavy screens, pair these habits with the adapter sizing advice in How to Size a RecyclerView Adapter for Smooth Lists and the binding pitfalls in Data Binding in RecyclerView: Setup and Common Pitfalls. And if you are still deciding how much state a widget or screen should own, StatelessWidget vs StatefulWidget: Which One Should You Pick? and Handling Configuration Changes in Kotlin Without Losing State are worth a read.

  • No GlobalScope, no runBlocking on the main thread
  • Every network call has a timeout and a retry policy
  • CancellationException is never swallowed
  • Flows collected with repeatOnLifecycle
  • Dispatchers injected for tests
  • Declare dispatchers inside suspend functions: IO for blocking work, Default for CPU work, Main only for UI.
  • Give every network call a timeout (10-15 s typical) and never swallow CancellationException.
  • Tie coroutines to lifecycleScope, viewModelScope or repeatOnLifecycle instead of GlobalScope.
  • Use stateIn with WhileSubscribed(5000) and a 250-400 ms debounce for responsive, wasteful-free flows.
Priya Shah · Android and Kotlin author
Covers Kotlin, Jetpack libraries and Android architecture with a hands-on approach. Focuses on migration guides, database work and networking patterns for small teams.

Related articles

↑