当前位置:嗨网首页>书籍在线阅读

14-挂起函数

  
选择背景色: 黄橙 洋红 淡粉 水蓝 草绿 白色 选择字体: 宋体 黑体 微软雅黑 楷体 选择字体大小: 恢复默认

12.4 挂起函数

使用关键字suspend修饰的函数称为挂起函数,挂起函数只能从协程代码内部调用,普通的非协程代码则不能调用。协程函数的格式如下。

suspend fun 函数名(参数名: 参数类型):返回值类型{
          函数体
    }

挂起函数只允许由协程或者另一个挂起函数调用,下面是协程调用挂起函数的例子。

suspend fun hangUpDemo() {
    run(CommonPool) {
        delay(1000L)
        println("run suspend")
    }
    println("hangUpDemo")
    Thread.sleep(2000L)
}
fun callSuspendFun() {
    launch(CommonPool) {
        hangUpDemo()
    }
}

事实上,要启动协程,必须有一个挂起函数,它通常是匿名的Lambda表达式。