What are Coroutines?
Coroutines are 'lightweight threads.' Unlike traditional OS threads, which are expensive to create and switch, thousands of coroutines can run on a single thread. They use 'Suspension' instead of 'Blocking'—when a coroutine waits for a network response from your Python API, it releases the underlying thread so other tasks can run. This is the secret to maintaining 120 FPS in your native Android Runner.
- The 'suspend' Keyword
The suspend modifier marks a function that can pause execution without blocking the current thread. Suspend functions can only be called from other suspend functions or from within a coroutine builder.
- Coroutine Dispatchers
Dispatchers determine which thread the coroutine runs on. As an Architect, choosing the right dispatcher is critical for performance and preventing 'NetworkOnMainThread' exceptions.
- Dispatchers.Main: Used for UI interactions (equivalent to Flutter's main isolate).
- Dispatchers.IO: Optimized for disk or network I/O (like calling your AI endpoints).
- Dispatchers.Default: Used for CPU-intensive work (like parsing large JSON widget trees).
- Dispatchers.Unconfined: Starts in the caller thread, but only until the first suspension point.
- Coroutine Builders: launch vs. async
There are two main ways to start a coroutine. launch is 'fire and forget' (returns a Job), while async is used when you expect a result (returns a Deferred, which is Kotlin's version of a Future).
- Structured Concurrency
In 2026, we avoid 'GlobalScope'. We use Structured Concurrency by launching coroutines within a CoroutineScope linked to a lifecycle (like viewModelScope or lifecycleScope). If the Activity or ViewModel is destroyed, all child coroutines are automatically canceled, preventing memory leaks in the Revochamp app.
Concurrency Comparison: Kotlin vs. Dart
| Feature | Kotlin Coroutines | Dart (Flutter) |
|---|---|---|
| Model | Multi-threaded (Shared Memory) | Single-threaded (Isolates) |
| Primary Tool | suspend / launch / async | async / await / Future |
| Scaling | Millions of coroutines | Heavy tasks need new Isolates |
| Thread Control | Explicit via Dispatchers | Mostly implicit (Event Loop) |
| Cancellation | Built-in (Job / Scope) | Manual (StreamSubscription/Cancelable) |
| Communication | Channels / Shared State | Ports / Messages |