# Dominando Kotlin Coroutines: Guia Completo 2026 > Aprenda a dominar Kotlin coroutines para desenvolvimento Android: funções suspend, scopes, dispatchers e padrões avançados. - Published: 2026-01-04 - Updated: 2026-04-02 - Author: Anthony Fillion-Maillet - Tags: kotlin, coroutines, android, async, concurrency - Reading time: 12 min --- As coroutines do Kotlin revolucionaram a programação assíncrona no Android. Ficaram para trás os callbacks aninhados e o obsoleto AsyncTask: com coroutines, código assíncrono é escrito de forma sequencial sem comprometer performance ou manutenibilidade. > **Por que coroutines?** > > Coroutines são leves (milhares podem rodar em uma única thread), canceláveis nativamente e integradas com Jetpack e o ecossistema moderno do Android. ## Entendendo os Fundamentos Antes de partir para o código, é essencial entender o que torna as coroutines tão poderosas. ### O que é uma Coroutine? Uma coroutine é uma instância de computação suspendível. Diferente de threads, coroutines não bloqueiam: elas suspendem sua execução e liberam a thread para outras tarefas. ```kotlin // BasicCoroutine.kt import kotlinx.coroutines.* fun main() = runBlocking { launch { delay(1000L) // Suspend without blocking println("World!") } println("Hello,") } // Output: Hello, World! ``` ### Funções Suspend: O Coração das Coroutines A palavra-chave `suspend` indica que uma função pode suspender a execução da coroutine sem bloquear a thread. ```kotlin // SuspendFunction.kt suspend fun fetchUserData(userId: String): User { return withContext(Dispatchers.IO) { // Network call - runs on an IO thread apiService.getUser(userId) } } suspend fun fetchUserWithPosts(userId: String): UserWithPosts { // Sequential execution val user = fetchUserData(userId) val posts = fetchUserPosts(userId) return UserWithPosts(user, posts) } ``` > **Regra de ouro**: Uma função suspend só pode ser chamada a partir de outra função suspend ou de dentro de uma coroutine. ## Coroutine Scopes O scope define o ciclo de vida das coroutines. Isso é crucial para evitar vazamentos de memória. ### viewModelScope: O Scope para ViewModels ```kotlin // UserViewModel.kt class UserViewModel( private val userRepository: UserRepository ) : ViewModel() { private val _uiState = MutableStateFlow(UserUiState.Loading) val uiState: StateFlow = _uiState.asStateFlow() fun loadUser(userId: String) { viewModelScope.launch { _uiState.value = UserUiState.Loading try { val user = userRepository.getUser(userId) _uiState.value = UserUiState.Success(user) } catch (e: Exception) { _uiState.value = UserUiState.Error(e.message) } } } } sealed class UserUiState { object Loading : UserUiState() data class Success(val user: User) : UserUiState() data class Error(val message: String?) : UserUiState() } ``` ### lifecycleScope: Para Activities e Fragments ```kotlin // UserFragment.kt class UserFragment : Fragment() { private val viewModel: UserViewModel by viewModels() override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) viewLifecycleOwner.lifecycleScope.launch { viewLifecycleOwner.repeatOnLifecycle(Lifecycle.State.STARTED) { viewModel.uiState.collect { state -> when (state) { is UserUiState.Loading -> showLoading() is UserUiState.Success -> showUser(state.user) is UserUiState.Error -> showError(state.message) } } } } } } ``` > **Cuidado com vazamentos** > > Nunca utilizar `GlobalScope` em uma aplicação Android. Coroutines lançadas com `GlobalScope` não estão vinculadas a nenhum ciclo de vida e podem causar vazamentos de memória. ## Dispatchers: Controlando a Execução Os dispatchers determinam em qual thread a coroutine será executada. ### Os 4 Dispatchers Principais ```kotlin // Dispatchers.kt // Main: main thread (UI) viewModelScope.launch(Dispatchers.Main) { textView.text = "UI update" } // IO: I/O operations (network, database) viewModelScope.launch(Dispatchers.IO) { val data = repository.fetchFromNetwork() } // Default: CPU-intensive computations viewModelScope.launch(Dispatchers.Default) { val result = heavyComputation(data) } // Unconfined: inherits caller context (rare use) ``` ### withContext: Troca de Dispatcher ```kotlin // ImageProcessor.kt class ImageProcessor { suspend fun processImage(bitmap: Bitmap): Bitmap { return withContext(Dispatchers.Default) { // CPU-intensive processing on Default applyFilters(bitmap) } } suspend fun saveToGallery(bitmap: Bitmap) { withContext(Dispatchers.IO) { // Disk write on IO saveToFile(bitmap) } } } // Usage in ViewModel viewModelScope.launch { val processed = imageProcessor.processImage(originalBitmap) imageProcessor.saveToGallery(processed) // Automatic return to Main for UI update _uiState.value = UiState.Success(processed) } ``` ## Execução Paralela com async/await Para executar tarefas em paralelo e combinar resultados, utiliza-se `async`. ```kotlin // ParallelExecution.kt suspend fun loadDashboard(): Dashboard { return coroutineScope { // Parallel launch val userDeferred = async { userRepository.getUser() } val statsDeferred = async { statsRepository.getStats() } val notificationsDeferred = async { notificationRepository.getNotifications() } // Await results Dashboard( user = userDeferred.await(), stats = statsDeferred.await(), notifications = notificationsDeferred.await() ) } } ``` > **Performance** > > Com `async`, as 3 chamadas executam em paralelo. Se cada uma leva 1 segundo, o tempo total é ~1 segundo em vez de 3 segundos sequenciais. ## Tratamento de Erros ### try/catch Clássico ```kotlin // ErrorHandling.kt viewModelScope.launch { try { val user = userRepository.getUser(userId) _uiState.value = UiState.Success(user) } catch (e: HttpException) { _uiState.value = UiState.Error("Server error: ${e.code()}") } catch (e: IOException) { _uiState.value = UiState.Error("Network error") } catch (e: Exception) { _uiState.value = UiState.Error("Unexpected error") } } ``` ### CoroutineExceptionHandler ```kotlin // ExceptionHandler.kt class UserViewModel : ViewModel() { private val exceptionHandler = CoroutineExceptionHandler { _, throwable -> _uiState.value = UiState.Error(throwable.message) Timber.e(throwable, "Error in coroutine") } fun loadUser(userId: String) { viewModelScope.launch(exceptionHandler) { val user = userRepository.getUser(userId) _uiState.value = UiState.Success(user) } } } ``` ### Padrão Result Wrapper ```kotlin // ResultPattern.kt sealed class Result { data class Success(val data: T) : Result() data class Error(val exception: Throwable) : Result() } suspend fun safeApiCall(apiCall: suspend () -> T): Result { return try { Result.Success(apiCall()) } catch (e: Exception) { Result.Error(e) } } // Usage class UserRepository(private val api: UserApi) { suspend fun getUser(id: String): Result = safeApiCall { api.getUser(id) } } // In ViewModel viewModelScope.launch { when (val result = userRepository.getUser(userId)) { is Result.Success -> _uiState.value = UiState.Success(result.data) is Result.Error -> _uiState.value = UiState.Error(result.exception.message) } } ``` ## Cancelamento: Limpeza Correta Coroutines suportam cancelamento cooperativo. Isso é essencial para evitar vazamento de recursos. ### Cancelamento Automático com Scopes ```kotlin // SearchViewModel.kt class SearchViewModel : ViewModel() { private var searchJob: Job? = null fun search(query: String) { // Cancel previous search searchJob?.cancel() searchJob = viewModelScope.launch { delay(300) // Debounce val results = searchRepository.search(query) _searchResults.value = results } } } ``` ### Verificação de Cancelamento ```kotlin // CancellationCheck.kt suspend fun processLargeList(items: List) { items.forEach { item -> // Check if coroutine is cancelled ensureActive() processItem(item) } } suspend fun downloadFiles(urls: List) = coroutineScope { urls.map { url -> async { try { downloadFile(url) } catch (e: CancellationException) { cleanupPartialDownload(url) throw e // Re-throw to propagate cancellation } } }.awaitAll() } ``` > **Nunca engolir CancellationException**: ao capturar `Exception`, é necessário relançar `CancellationException` para que o cancelamento se propague corretamente. ## Flow: Programação Reativa Flow é o equivalente do RxJava Observable em coroutines, porém mais simples e integrado. ### Criando e Coletando um Flow ```kotlin // FlowBasics.kt fun getUsers(): Flow> = flow { while (true) { val users = userApi.getUsers() emit(users) delay(5000) // Poll every 5 seconds } } // Flow from Room @Dao interface UserDao { @Query("SELECT * FROM users") fun getAllUsers(): Flow> } // Collecting in ViewModel viewModelScope.launch { userDao.getAllUsers() .catch { e -> _uiState.value = UiState.Error(e.message) } .collect { users -> _uiState.value = UiState.Success(users) } } ``` ### StateFlow vs SharedFlow ```kotlin // StateFlowVsSharedFlow.kt class EventViewModel : ViewModel() { // StateFlow: keeps last value, ideal for UI state private val _uiState = MutableStateFlow(UiState.Initial) val uiState: StateFlow = _uiState.asStateFlow() // SharedFlow: for one-shot events (navigation, snackbar) private val _events = MutableSharedFlow() val events: SharedFlow = _events.asSharedFlow() fun onButtonClick() { viewModelScope.launch { _events.emit(UiEvent.NavigateToDetail) } } } sealed class UiEvent { object NavigateToDetail : UiEvent() data class ShowSnackbar(val message: String) : UiEvent() } ``` ### Operadores Essenciais de Flow ```kotlin // FlowOperators.kt userRepository.getUsers() .map { users -> users.filter { it.isActive } } .distinctUntilChanged() .debounce(300) .flatMapLatest { users -> fetchUserDetails(users) } .catch { e -> emit(emptyList()) } .onEach { users -> analytics.logUserCount(users.size) } .stateIn( scope = viewModelScope, started = SharingStarted.WhileSubscribed(5000), initialValue = emptyList() ) ``` ## Padrões Avançados ### Retry com Backoff Exponencial ```kotlin // RetryPattern.kt suspend fun retryWithBackoff( times: Int = 3, initialDelay: Long = 100, maxDelay: Long = 1000, factor: Double = 2.0, block: suspend () -> T ): T { var currentDelay = initialDelay repeat(times - 1) { attempt -> try { return block() } catch (e: Exception) { Timber.w("Attempt ${attempt + 1} failed, retrying in ${currentDelay}ms") } delay(currentDelay) currentDelay = (currentDelay * factor).toLong().coerceAtMost(maxDelay) } return block() } // Usage val user = retryWithBackoff { userApi.getUser(userId) } ``` ### Timeout ```kotlin // TimeoutPattern.kt suspend fun fetchWithTimeout() { try { val result = withTimeout(5000L) { api.fetchData() } processResult(result) } catch (e: TimeoutCancellationException) { showError("Request took too long") } } // Or with a default value val result = withTimeoutOrNull(5000L) { api.fetchData() } ?: defaultValue ``` ## Conclusão As coroutines do Kotlin tornaram-se essenciais para o desenvolvimento Android moderno. Oferecem uma abordagem elegante e performática para programação assíncrona, perfeitamente integrada com o ecossistema Jetpack. ### Checklist - ✅ Usar `viewModelScope` e `lifecycleScope` para evitar vazamentos - ✅ Escolher o Dispatcher correto (Main, IO, Default) - ✅ Tratar erros com try/catch ou Result wrapper - ✅ Implementar cancelamento cooperativo - ✅ Usar Flow para fluxos de dados reativos - ✅ Preferir StateFlow para estado UI, SharedFlow para eventos Dominar coroutines proporciona uma vantagem significativa em projetos Android e entrevistas técnicas. A prática constante e a exploração de padrões avançados consolidam essas habilidades. --- Source: SharpSkill (https://sharpskill.dev), tech interview preparation for your real stack. HTML version of this page: https://sharpskill.dev/pt/blog/android/mastering-kotlin-coroutines