kotlin - 测试代码时为什么会出现错误 “Unresolved reference: launch”?

标签 kotlin kotlin-coroutines

我正在学习Kotlin的协程,我是https://try.kotlinlang.org/中在线运行代码的初学者

我尝试在网站上测试代码A,但是像图像A一样出现很多错误,我该如何解决?

代码A

import kotlinx.coroutines.*

fun main(args: Array<String>) {

    val job = launch {
      val child = launch {
         try {
            delay(Long.MAX_VALUE)
         } finally {
             println("Child is cancelled")
         }
      }

      yield()
      println("Cancelling child")
      child.cancel()
      child.join()
      yield()
      println("Parent is not cancelled")
    }

    job.join()

}

图片
enter image description here

最佳答案

尝试运行以下代码:

import kotlinx.coroutines.*
import kotlin.coroutines.CoroutineContext

fun main() = runBlocking<Unit> { //here i made change
    val job = launch {
      val child = launch {
         try {
            delay(Long.MAX_VALUE)
         } finally {
             println("Child is cancelled")
         }
      }

      yield()
      println("Cancelling child")
      child.cancel()
      child.join()
      yield()
      println("Parent is not cancelled")
    }

    job.join()

}

输出将是:)
Cancelling child
Child is cancelled
Parent is not cancelled

关于kotlin - 测试代码时为什么会出现错误 “Unresolved reference: launch”?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60732166/

相关文章:

android - 如何在 Kotlin 中处理两个不同的 Retrofit 响应?

java - 你能@Autowired一个@MessageGateway到RestController中吗

android-studio - Kotlin,Android,如何正确调试协程?

android - 从 Executor(ThreadPoolExecutor) 调用挂起协程的最佳方法

android - 为 Espresso 测试制作 CoroutineDispatcher IdlingResource

android - Firebase ML-Kit 并行运行多个人脸检测 session

android - 如何合并到 kotlin 协程在一起?

multithreading - 将 channel 桥接到序列

android - 为什么 ViewModel 和 Fragment 中的相同变量不同?

kotlin - 打印 IntArray 内容的 Kotlin 方式是什么?