⚡ Coroutines Basics
🎯 Mục tiêu: Hiểu Coroutines - cách xử lý async/concurrent programming trong Kotlin.
💡 Khái niệm
Phần tiêu đề “💡 Khái niệm”Coroutines là light-weight threads cho phép viết async code như sync code.
import kotlinx.coroutines.*
fun main() = runBlocking { launch { delay(1000) println("World!") } println("Hello,")}// Output: Hello, (wait 1s) World!📝 Suspend Functions
Phần tiêu đề “📝 Suspend Functions”suspend fun fetchUser(): User { delay(1000) // Giả lập network call return User("Alice", 25)}
fun main() = runBlocking { val user = fetchUser() // Chờ 1s println(user)}🔧 Coroutine Builders
Phần tiêu đề “🔧 Coroutine Builders”// runBlocking - block thread, chờ hoàn thànhfun main() = runBlocking { // code}
// launch - fire and forget, trả về Jobval job = launch { delay(1000) println("Done")}job.join() // Chờ hoàn thành
// async - trả về Deferred với kết quảval deferred = async { delay(1000) "Result"}val result = deferred.await() // Chờ và lấy kết quả🎯 Structured Concurrency
Phần tiêu đề “🎯 Structured Concurrency”suspend fun loadData() = coroutineScope { val users = async { fetchUsers() } val posts = async { fetchPosts() }
// Cả 2 chạy song song println("Users: ${users.await()}") println("Posts: ${posts.await()}")}📦 Dispatchers
Phần tiêu đề “📦 Dispatchers”// Main - UI thread (Android)withContext(Dispatchers.Main) { updateUI()}
// IO - cho network, filewithContext(Dispatchers.IO) { fetchFromNetwork()}
// Default - CPU intensivewithContext(Dispatchers.Default) { heavyComputation()}📱 Trong Android
Phần tiêu đề “📱 Trong Android”class UserViewModel : ViewModel() {
fun loadUser() { viewModelScope.launch { _state.value = UiState.Loading
try { val user = withContext(Dispatchers.IO) { repository.fetchUser() } _state.value = UiState.Success(user) } catch (e: Exception) { _state.value = UiState.Error(e) } } }}⚠️ Cancellation
Phần tiêu đề “⚠️ Cancellation”val job = launch { repeat(1000) { i -> println("Iteration $i") delay(500) }}
delay(2000)job.cancel() // Cancel sau 2 giây✅ Checklist
Phần tiêu đề “✅ Checklist”- Hiểu
suspendfunctions - Sử dụng
launch,async,runBlocking - Hiểu Dispatchers: Main, IO, Default
- Sử dụng
withContextđể đổi dispatcher - Cancel coroutines đúng cách
Kết thúc khóa học Ngôn ngữ Kotlin!
Tiếp theo: Kotlin Coroutines chuyên sâu | Android Development