Coroutines Basics trong Kotlin
1. Giới thiệu
Coroutines là cách viết async code dễ đọc như code đồng bộ.
2. Setup
Thêm dependency trong build.gradle.kts:
implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.7.3")3. launch và runBlocking
import kotlinx.coroutines.*
fun main() = runBlocking {
launch {
delay(1000L)
println("World!")
}
println("Hello")
}
// Output: Hello, World!4. suspend Functions
suspend fun fetchData(): String {
delay(1000L) // Simulating network call
return "Data loaded!"
}
fun main() = runBlocking {
val data = fetchData()
println(data)
}5. async và await
import kotlinx.coroutines.*
fun main() = runBlocking {
val deferred1 = async { fetchUser() }
val deferred2 = async { fetchPosts() }
val user = deferred1.await()
val posts = deferred2.await()
println("User: $user, Posts: $posts")
}
suspend fun fetchUser(): String {
delay(1000L)
return "Alice"
}
suspend fun fetchPosts(): List<String> {
delay(1500L)
return listOf("Post 1", "Post 2")
}6. Coroutine Scope
import kotlinx.coroutines.*
fun main() = runBlocking {
// Child coroutines
launch {
delay(200L)
println("Task 1")
}
launch {
delay(100L)
println("Task 2")
}
println("Started")
}
// Output: Started, Task 2, Task 17. withContext - Switch Context
import kotlinx.coroutines.*
suspend fun loadData(): String = withContext(Dispatchers.IO) {
// IO operations
"Data"
}
suspend fun updateUI(data: String) = withContext(Dispatchers.Main) {
// UI operations
println("Updating UI with $data")
}8. Dispatchers
import kotlinx.coroutines.*
fun main() = runBlocking {
launch(Dispatchers.Default) {
// CPU-intensive work
println("Default: ${Thread.currentThread().name}")
}
launch(Dispatchers.IO) {
// Network/Disk IO
println("IO: ${Thread.currentThread().name}")
}
launch(Dispatchers.Unconfined) {
// Not confined to any thread
println("Unconfined: ${Thread.currentThread().name}")
}
}9. Exception Handling
import kotlinx.coroutines.*
fun main() = runBlocking {
val handler = CoroutineExceptionHandler { _, exception ->
println("Caught: $exception")
}
val job = launch(handler) {
throw Exception("Something went wrong")
}
job.join()
}10. Cancellation
import kotlinx.coroutines.*
fun main() = runBlocking {
val job = launch {
repeat(1000) { i ->
println("Job: $i")
delay(500L)
}
}
delay(1300L)
println("Cancelling...")
job.cancel()
job.join() // Wait for cancellation
println("Done")
}11. Flow (Reactive Streams)
import kotlinx.coroutines.*
import kotlinx.coroutines.flow.*
fun numbers(): Flow<Int> = flow {
for (i in 1..3) {
delay(100)
emit(i)
}
}
fun main() = runBlocking {
numbers()
.map { it * 2 }
.filter { it > 2 }
.collect { println(it) }
}📝 Tóm tắt
suspendcho async functionslaunchfire-and-forget coroutineasync/awaitcho concurrent resultswithContextswitch dispatcher- Dispatchers: Default, IO, Main
cancel()để hủy coroutine- Flow cho reactive streams
Last updated on