coroutineScope 一损俱损

coroutineScope当中的协程异常会触发父协程的取消,进而整个协程作用域会取消掉

supervisorScope 自作自受

子协程的异常不会向上传递

join 和 await

join 只关心协程是否执行完毕,出现异常是也不会抛出
await 关心运行结果

image.png

  1. fun main(array: Array<String>) {
  2. GlobalScope.launch(Dispatchers.IO) {
  3. try {
  4. val name = getUserCoroutine().name
  5. println(name)
  6. } catch (e: Exception) {
  7. println("hello")
  8. }
  9. }
  10. Thread.sleep(1000)
  11. }
suspend fun getUserCoroutine() = suspendCoroutine<User> { continuation ->
    getUser(object : Callback11<User> {
        override fun onSuccess(value: User) {
            continuation.resume(value)
        }

        override fun onError(t: Throwable) {
            continuation.resumeWithException(t)
        }

    })
}
interface Callback11<T> {
    fun onSuccess(value: T)
    fun onError(t: Throwable)
}

fun getUser(callback: Callback11<User>) {
    val user = User("xiaodong", 10)
    if (Math.random() * 10 > 5) {
        callback.onSuccess(user)
    } else {
        callback.onError(Exception("错乱"))
    }
}


data class User(val name: String, val age: Int)

参考:
[破解 Kotlin 协程(4) - 异常处理篇]