Coroutines Basics trong Kotlin
🎯 Mục tiêu: Hiểu Coroutines - cách xử lý async/concurrent programming trong Kotlin.
💡 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
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
// runBlocking - block thread, chờ hoàn thành
fun main() = runBlocking {
// code
}
// launch - fire and forget, trả về Job
val 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
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
// Main - UI thread (Android)
withContext(Dispatchers.Main) {
updateUI()
}
// IO - cho network, file
withContext(Dispatchers.IO) {
fetchFromNetwork()
}
// Default - CPU intensive
withContext(Dispatchers.Default) {
heavyComputation()
}📱 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
val job = launch {
repeat(1000) { i ->
println("Iteration $i")
delay(500)
}
}
delay(2000)
job.cancel() // Cancel sau 2 giây✅ 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
Last updated on