kotlin协程使用举例

Kotlin协程通过简化异步任务的处理,使代码更易于阅读和维护。
以下是一些常见的使用场景及代码示例,展示如何使用Kotlin协程:

1. 启动一个简单的协程

使用launch在协程作用域内启动一个协程。

import kotlinx.coroutines.*

fun main() = runBlocking {
    launch {
        delay(1000L)  // 模拟一些异步工作
        println("World!")
    }
    println("Hello,")
}
// 输出:
// Hello,
// (1秒后)
// World!

2. 使用async与await进行并行任务

async用于启动一个并发任务,并返回一个Deferred对象,使用await可以获取结果。

import kotlinx.coroutines.*

fun main() = runBlocking {
    val deferred1 = async { fetchDataFromNetwork1() }
    val deferred2 = async { fetchDataFromNetwork2() }
    
    println("Data1: ${deferred1.await()}")
    println("Data2: ${deferred2.await()}")
}

suspend fun fetchDataFromNetwork1(): String {
    delay(1000L)  // 模拟网络请求
    return "NetworkData1"
}

suspend fun fetchDataFromNetwork2(): String {
    delay(1000L)  // 模拟网络请求
    return "NetworkData2"
}

3. 使用withContext切换上下文

使用withContext可以切换协程的执行上下文,比如在IO线程中进行一些阻塞性操作。


import kotlinx.coroutines.*

fun main() = runBlocking {
    println("Main Thread: ${Thread.currentThread().name}")

    val result = withContext(Dispatchers.IO) {
        println("IO Thread: ${Thread.currentThread().name}")
        performIoOperation()
    }

    println("Returned to Main Thread: ${result}")
}

suspend fun performIoOperation(): String {
    delay(500L)  // 模拟IO操作
    return "IO Result"
}

4. 使用coroutineScope获得结构化并发

coroutineScope可以确保所有子协程执行完毕后才会结束。

import kotlinx.coroutines.*

fun main() = runBlocking {
    launch {
        delay(200L)
        println("Task from runBlocking")
    }

    coroutineScope {
        launch {
            delay(500L)
            println("Task from nested launch")
        }

        delay(100L)
        println("Task from coroutine scope") // 这一行会在内嵌的协程执行之前输出
    }

    println("Coroutine scope is over") // 这一行在内嵌的协程执行完毕后输出
}

5. 处理异常

协程中处理异常通常使用try-catch块。

import kotlinx.coroutines.*

fun main() = runBlocking {
    try {
        launch {
            delay(500L)
            throw Exception("Something went wrong!")
        }
    } catch (e: Exception) {
        println("Caught exception: ${e.message}")
    }
}

你可能感兴趣的:(kotlin,开发语言,android)