| name | coroutines-patterns |
| description | Kotlin Coroutines and Flow patterns for structured concurrency, error handling, and async operations. |
Coroutines Patterns
Structured concurrency for Kotlin.
Coroutine Scopes
class HomeViewModel : ViewModel() {
fun loadData() {
viewModelScope.launch {
}
}
}
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
lifecycleScope.launch {
}
}
}
GlobalScope.launch { }
Dispatchers
withContext(Dispatchers.Main) {
textView.text = "Updated"
}
withContext(Dispatchers.IO) {
api.fetchData()
database.query()
}
withContext(Dispatchers.Default) {
list.sortedBy { it.score }
}
Flow Patterns
private val _state = MutableStateFlow(HomeState())
val state: StateFlow<HomeState> = _state.asStateFlow()
private val _events = MutableSharedFlow<Event>()
val events: SharedFlow<Event> = _events.asSharedFlow()
@Composable
fun HomeScreen(viewModel: HomeViewModel) {
val state by viewModel.state.collectAsStateWithLifecycle()
}
Flow Operators
flow
.filter { it.isActive }
.map { transform(it) }
.distinctUntilChanged()
.debounce(300)
.catch { emit(fallback) }
.collect { process(it) }
Error Handling
viewModelScope.launch {
try {
val result = repository.fetchData()
_state.value = Success(result)
} catch (e: Exception) {
_state.value = Error(e.message)
}
}
supervisorScope {
launch { task1() }
launch { task2() }
}
Cancellation
suspend fun processItems(items: List<Item>) {
items.forEach { item ->
ensureActive()
process(item)
}
}
try {
coroutineWork()
} catch (e: CancellationException) {
throw e
} catch (e: Exception) {
handleError(e)
}
Remember: Structured concurrency = lifecycle-bound, cancellable, debuggable.