kotlin用CoroutineScope启动协程async等待结果返回
例如:
import kotlinx.coroutines.*
object MyCoroutineScope {
private val coroutineContext = Job() + Dispatchers.Default + CoroutineName("my_context")
val coroutineScope = CoroutineScope(coroutineContext)
}
suspend fun demo(): String {
val job = MyCoroutineScope.coroutineScope.async(Dispatchers.Default) {
repeat(3) {
println(it)
}
"zhangphil"
}
return job.await()
}
fun main(args: Array<String>) {
runBlocking {
launch {
var ret = demo()
println(ret)
}
}
}
输出:
0
1
2
zhangphil