Cursor rules for Kotlin coroutines with lifecycle-bound scopes, main-safe suspend functions, injected dispatchers and correct CancellationException handling.
.cursor/rules/kotlin-coroutines-usage.mdc. Downloaded files need to be placed in that repository path.---
description: "Cursor rules for Kotlin coroutines with lifecycle-bound scopes, main-safe suspend functions, injected dispatchers and correct CancellationException handling."
globs: "**/*"
alwaysApply: false
---
# Kotlin Coroutines Usage Rules
Applies to: Kotlin code using `kotlinx.coroutines` (Android ViewModels and repositories, server code, libraries) and its tests.
Version baseline: checked against the kotlinx.coroutines guides on kotlinlang.org and Android's coroutines best practices. Read `build.gradle(.kts)` / `libs.versions.toml` for the coroutines version and follow it. Snippets omit imports; `UserApi`, `User`, `UserUiState`, `Dashboard` and `orderRepo` stand for project types.
## Structured concurrency
- Launch every coroutine in a scope whose lifetime matches the work: `viewModelScope` in ViewModels, `lifecycleScope`/`repeatOnLifecycle` in UI, an injected application `CoroutineScope` for work that must outlive a screen, and `coroutineScope { }` inside suspend functions.
- Do not use `GlobalScope`. Do not create ad hoc `CoroutineScope(Dispatchers.IO)` instances that nobody cancels.
- `viewModelScope` is cancelled automatically when the ViewModel is cleared and `lifecycleScope` when the lifecycle is destroyed; do not cancel them yourself.
## Naming and API shape
- Name suspend functions for what they do (`loadUser()`, `saveOrder()`). Do not prefix them with `async` or `launch`.
- Expose `suspend` functions or `Flow` from repositories and data sources; let the caller decide where to launch.
- A function that launches work and returns immediately should be an extension on `CoroutineScope` or take a scope, so the caller sees that it starts concurrent work.
- In ViewModels, launch coroutines in `viewModelScope` for UI-triggered work instead of exposing suspend functions to the UI.
- Expose immutable types: `StateFlow`/`Flow` publicly, `MutableStateFlow` privately.
## Dispatchers and main-safety
- Suspend functions must be main-safe: move blocking work inside them with `withContext(ioDispatcher)` rather than requiring callers to switch threads.
- Inject dispatchers (constructor parameter with a default) instead of hard-coding `Dispatchers.IO`, so tests can substitute a test dispatcher.
```kotlin
class UserRepository(
private val api: UserApi,
private val ioDispatcher: CoroutineDispatcher = Dispatchers.IO,
) {
suspend fun loadUser(id: String): User = withContext(ioDispatcher) {
api.fetchUser(id) // blocking client call
}
}
class UserViewModel(private val repo: UserRepository) : ViewModel() {
private val _state = MutableStateFlow<UserUiState>(UserUiState.Loading)
val state: StateFlow<UserUiState> = _state.asStateFlow()
fun load(id: String) {
viewModelScope.launch {
_state.value = try {
UserUiState.Loaded(repo.loadUser(id))
} catch (e: CancellationException) {
throw e
} catch (e: IOException) {
UserUiState.Error("Could not load user")
}
}
}
}
```
## launch vs async
- `launch` for fire-and-forget work inside a scope (result reported through state).
- `async`/`await` only for concurrent work whose results you combine; start several, then await them, inside `coroutineScope { }` so a failure cancels the siblings.
```kotlin
suspend fun loadDashboard(id: String): Dashboard = coroutineScope {
val profile = async { repo.loadUser(id) }
val orders = async { orderRepo.recent(id) }
Dashboard(profile.await(), orders.await())
}
```
## Cancellation and exceptions
- Cancellation is cooperative. In long loops, call `ensureActive()` or `yield()`, and use suspending APIs (`delay`, not `Thread.sleep`) so cancellation can take effect.
- Never swallow `CancellationException`. If you catch `Exception` or `Throwable`, rethrow `CancellationException` first; avoid `runCatching` around suspend calls for the same reason.
- Catch the specific exceptions you can handle (for example `IOException`) close to where you can turn them into UI state.
- `CoroutineExceptionHandler` only receives uncaught exceptions from root coroutines started with `launch`. It has no effect on child coroutines or on `async`; it is a last-resort logger, not a substitute for handling errors.
- Use `supervisorScope`/`SupervisorJob` when one child's failure must not cancel its siblings.
- Use `withTimeout`/`withTimeoutOrNull` for deadlines instead of manual timers.
## Blocking calls
- Never call `Thread.sleep`, `runBlocking` or blocking I/O on `Dispatchers.Main`. `runBlocking` belongs in `main` functions and tests, not in coroutines or Android UI code.
- Wrap unavoidable blocking calls in `withContext(ioDispatcher)`.
## Flows
- Collect UI flows with `repeatOnLifecycle(Lifecycle.State.STARTED)` (or `collectAsStateWithLifecycle` in Compose) so collection stops in the background.
- Use `stateIn`/`shareIn` with an explicit `SharingStarted` policy for flows shared across collectors.
## Testing
- Use `runTest` from `kotlinx-coroutines-test` and inject a `StandardTestDispatcher`/`UnconfinedTestDispatcher`.
- Replace `Dispatchers.Main` with `Dispatchers.setMain(testDispatcher)` in tests and reset it afterwards.
## Verify before finishing
Run these when they are available in the project:
- `./gradlew test` (unit tests using `runTest`)
- `./gradlew lint` / `detekt` / `ktlintCheck`, if configured
- A test that cancels the scope and asserts the work stops and no error state is emitted
Cursor rules for Next.js 14+ App Router projects updated for Next.js 16 with async params, validated Route Handlers, generateMetadata and proxy.ts in place of middleware.
Cursor rules for strict TypeScript: compiler checks beyond strict, interfaces vs type aliases, real type guards, discriminated unions, utility types and branded IDs.
Cursor rules for Tailwind CSS v4: automatic class sorting, mobile-first breakpoints, CVA variants with merging, class-based dark mode via @custom-variant, and CSS-first @theme configuration.
Cursor
coding
Illustrative input and expected result. This example is a verification guide, not a recorded model run.
Content reviewed .
An Android app using ViewModels and kotlinx.coroutines has this rule attached while a developer asks Cursor to load a user profile from a blocking API client.
UserApi.fetchUser(id) is a blocking call. Add a repository function and a ViewModel load(id) that exposes Loading, Loaded and Error states, and a unit test.
Illustrative; not a recorded model run. A repository with an injected ioDispatcher defaulting to Dispatchers.IO and a main-safe suspend fun loadUser using withContext; a ViewModel exposing StateFlow (MutableStateFlow kept private) and launching in viewModelScope; catch blocks that rethrow CancellationException and handle IOException as an Error state; no GlobalScope, no async-prefixed names, no manual cancellation of viewModelScope; a runTest test that injects a test dispatcher and sets Dispatchers.Main.
Cursor applies project rules stored as .mdc files in .cursor/rules. Each rule's frontmatter (description, globs, alwaysApply) decides whether it is always included, attached to matching files, chosen by the agent from its description, or only used when you @-mention it. Cursor also reads AGENTS.md in the project root and subdirectories for plain-Markdown instructions.
.cursor/rules/kotlin-coroutines-usage.mdcStarting point, not a tested configuration for your repository. Attached when files matching the globs are in context (alwaysApply: false with globs). Review the instructions, adapt the file paths and run your project's existing checks.
---
description: "Kotlin Coroutines Usage: Structured Concurrency, Dispatchers and Cancellation project conventions"
globs: "**/*"
alwaysApply: false
---
# Kotlin Coroutines Usage Rules
Applies to: Kotlin code using `kotlinx.coroutines` (Android ViewModels and repositories, server code, libraries) and its tests.
Version baseline: checked against the kotlinx.coroutines guides on kotlinlang.org and Android's coroutines best practices. Read `build.gradle(.kts)` / `libs.versions.toml` for the coroutines version and follow it. Snippets omit imports; `UserApi`, `User`, `UserUiState`, `Dashboard` and `orderRepo` stand for project types.
## Structured concurrency
- Launch every coroutine in a scope whose lifetime matches the work: `viewModelScope` in ViewModels, `lifecycleScope`/`repeatOnLifecycle` in UI, an injected application `CoroutineScope` for work that must outlive a screen, and `coroutineScope { }` inside suspend functions.
- Do not use `GlobalScope`. Do not create ad hoc `CoroutineScope(Dispatchers.IO)` instances that nobody cancels.
- `viewModelScope` is cancelled automatically when the ViewModel is cleared and `lifecycleScope` when the lifecycle is destroyed; do not cancel them yourself.
## Naming and API shape
- Name suspend functions for what they do (`loadUser()`, `saveOrder()`). Do not prefix them with `async` or `launch`.
- Expose `suspend` functions or `Flow` from repositories and data sources; let the caller decide where to launch.
- A function that launches work and returns immediately should be an extension on `CoroutineScope` or take a scope, so the caller sees that it starts concurrent work.
- In ViewModels, launch coroutines in `viewModelScope` for UI-triggered work instead of exposing suspend functions to the UI.
- Expose immutable types: `StateFlow`/`Flow` publicly, `MutableStateFlow` privately.
## Dispatchers and main-safety
- Suspend functions must be main-safe: move blocking work inside them with `withContext(ioDispatcher)` rather than requiring callers to switch threads.
- Inject dispatchers (constructor parameter with a default) instead of hard-coding `Dispatchers.IO`, so tests can substitute a test dispatcher.
```kotlin
class UserRepository(
private val api: UserApi,
private val ioDispatcher: CoroutineDispatcher = Dispatchers.IO,
) {
suspend fun loadUser(id: String): User = withContext(ioDispatcher) {
api.fetchUser(id) // blocking client call
}
}
class UserViewModel(private val repo: UserRepository) : ViewModel() {
private val _state = MutableStateFlow<UserUiState>(UserUiState.Loading)
val state: StateFlow<UserUiState> = _state.asStateFlow()
fun load(id: String) {
viewModelScope.launch {
_state.value = try {
UserUiState.Loaded(repo.loadUser(id))
} catch (e: CancellationException) {
throw e
} catch (e: IOException) {
UserUiState.Error("Could not load user")
}
}
}
}
```
## launch vs async
- `launch` for fire-and-forget work inside a scope (result reported through state).
- `async`/`await` only for concurrent work whose results you combine; start several, then await them, inside `coroutineScope { }` so a failure cancels the siblings.
```kotlin
suspend fun loadDashboard(id: String): Dashboard = coroutineScope {
val profile = async { repo.loadUser(id) }
val orders = async { orderRepo.recent(id) }
Dashboard(profile.await(), orders.await())
}
```
## Cancellation and exceptions
- Cancellation is cooperative. In long loops, call `ensureActive()` or `yield()`, and use suspending APIs (`delay`, not `Thread.sleep`) so cancellation can take effect.
- Never swallow `CancellationException`. If you catch `Exception` or `Throwable`, rethrow `CancellationException` first; avoid `runCatching` around suspend calls for the same reason.
- Catch the specific exceptions you can handle (for example `IOException`) close to where you can turn them into UI state.
- `CoroutineExceptionHandler` only receives uncaught exceptions from root coroutines started with `launch`. It has no effect on child coroutines or on `async`; it is a last-resort logger, not a substitute for handling errors.
- Use `supervisorScope`/`SupervisorJob` when one child's failure must not cancel its siblings.
- Use `withTimeout`/`withTimeoutOrNull` for deadlines instead of manual timers.
## Blocking calls
- Never call `Thread.sleep`, `runBlocking` or blocking I/O on `Dispatchers.Main`. `runBlocking` belongs in `main` functions and tests, not in coroutines or Android UI code.
- Wrap unavoidable blocking calls in `withContext(ioDispatcher)`.
## Flows
- Collect UI flows with `repeatOnLifecycle(Lifecycle.State.STARTED)` (or `collectAsStateWithLifecycle` in Compose) so collection stops in the background.
- Use `stateIn`/`shareIn` with an explicit `SharingStarted` policy for flows shared across collectors.
## Testing
- Use `runTest` from `kotlinx-coroutines-test` and inject a `StandardTestDispatcher`/`UnconfinedTestDispatcher`.
- Replace `Dispatchers.Main` with `Dispatchers.setMain(testDispatcher)` in tests and reset it afterwards.
## Verify before finishing
Run these when they are available in the project:
- `./gradlew test` (unit tests using `runTest`)
- `./gradlew lint` / `detekt` / `ktlintCheck`, if configured
- A test that cancels the scope and asserts the work stops and no error state is emitted
Ask for a small change to one matching file. Check the tool's loaded context or instruction view, inspect the diff for the requested convention, and run the relevant build or test. A well-formatted file does not guarantee the model follows every instruction.
Cursor's docs recommend keeping individual rules under 500 lines and splitting large rules into composable ones. Cursor's documentation states that it supports AGENTS.md in the project root and in subdirectories. Use AGENTS.md for plain-Markdown instructions you also want other tools to read, and .mdc rules when you need Cursor's scoping options (globs, description-based selection, always-apply).
Documentation checked 2026-11-05: Cursor docs: Rules
Cursor rules for Next.js 14+ App Router projects updated for Next.js 16 with async params, validated Route Handlers, generateMetadata and proxy.ts in place of middleware.
Cursor rules for strict TypeScript: compiler checks beyond strict, interfaces vs type aliases, real type guards, discriminated unions, utility types and branded IDs.
Cursor rules for Tailwind CSS v4: automatic class sorting, mobile-first breakpoints, CVA variants with merging, class-based dark mode via @custom-variant, and CSS-first @theme configuration.