Async Code & the Main Thread

Why mobile UIs run on a single main thread, and how promises, futures, coroutines and async/await keep apps responsive.

Beginner · about 6 hours · difficulty 3/5

Every mobile platform draws its UI from one main thread (also called the UI thread). If you block it with a network call, a big JSON parse or a database query, the app freezes and the OS may show an "App Not Responding" dialog or kill it.

The shared idea

All modern stacks let you start slow work and continue when it finishes, without blocking:

  • JavaScript: Promise and async/await. The JS thread in React Native is separate from the native UI thread, but blocking it still freezes your interactions.
  • Dart: Future, Stream, and Isolate for CPU-heavy work.
  • Kotlin: coroutines with dispatchers (Dispatchers.IO for I/O, Main for UI).
  • Swift: async/await, Task, actors and @MainActor.

Patterns you will use constantly

  • Show a loading state, await the work, then show data or an error.
  • Cancel work when the user leaves a screen, so results do not update a view that no longer exists.
  • Run independent requests in parallel (Promise.all, Future.wait, async let).

Pitfalls

  • Forgetting to catch rejected promises leads to silent failures.
  • Race conditions: a slow first search result arriving after a fast second one and overwriting it. Track the latest request or cancel old ones.

Good enough to move on: you can fetch two resources in parallel, handle errors, and explain why the UI stays responsive meanwhile.

Key concepts

  • The main (UI) thread
  • async/await
  • Error handling in async code
  • Parallel vs sequential requests
  • Cancellation
  • Race conditions in UI
  • Background threads, isolates and dispatchers

Mini project

Build a search box that queries a public API as the user types, cancels or ignores stale requests, and shows loading and error states.

Check yourself

A search screen sometimes shows results for an older query. What is happening and how do you fix it?

Free resources