Kotlin:async的返回映射(start=CoroutineStart.LAZY)
我想返回延迟启动的协程的映射,并在另一个函数中使用它们(启动/取消) 问题是下面的getMap()函数挂起。为什么会这样?有可能从函数返回这样的映射吗Kotlin:async的返回映射(start=CoroutineStart.LAZY),kotlin,kotlin-coroutines,Kotlin,Kotlin Coroutines,我想返回延迟启动的协程的映射,并在另一个函数中使用它们(启动/取消) 问题是下面的getMap()函数挂起。为什么会这样?有可能从函数返回这样的映射吗 import kotlinx.coroutines.* suspend fun getMap(): LinkedHashMap<String, Deferred<Any>> { return withContext(Dispatchers.Default) { val map = linkedMa
import kotlinx.coroutines.*
suspend fun getMap(): LinkedHashMap<String, Deferred<Any>> {
return withContext(Dispatchers.Default) {
val map = linkedMapOf<String, Deferred<Any>>()
map["1"] = async(start = CoroutineStart.LAZY) { 1 }
map["2"] = async(start = CoroutineStart.LAZY) { 2 }
map;
}
}
fun main() {
runBlocking {
val map = getMap()
println("not happening")
}
}
导入kotlinx.coroutines*
suspend fun getMap():LinkedHashMap{
返回withContext(Dispatchers.Default){
val map=linkedmapf()
map[“1”]=async(start=CoroutineStart.LAZY){1}
map[“2”]=async(start=CoroutineStart.LAZY){2}
地图;
}
}
主要内容(){
运行阻塞{
val map=getMap()
println(“未发生”)
}
}
withContext
直到在其中启动的所有协同程序完成后才会完成。您可以将您的案例简化为:
fun main() {
runBlocking {
withContext(Dispatchers.Default) {
launch(start = CoroutineStart.LAZY) { 1 }
}
println("not happening")
}
}
它也不完整。您陷入这种情况的原因是您不恰当地使用了上下文。您的getMap()
没有理由成为suspend fun
您需要为这些async
调用设置一个协同路由范围,而不是withContext
。例如,这将起作用:
fun getMap(): Map<String, Deferred<Any>> =
linkedMapOf<String, Deferred<Any>>().also { map ->
with(GlobalScope) {
map["1"] = async(start = CoroutineStart.LAZY) { 1 }
map["2"] = async(start = CoroutineStart.LAZY) { 2 }
}
}
fun main() {
val map = getMap()
println("now it's happening")
}
fun getMap():Map=
linkedMapOf()。也是{map->
带(环球镜){
map[“1”]=async(start=CoroutineStart.LAZY){1}
map[“2”]=async(start=CoroutineStart.LAZY){2}
}
}
主要内容(){
val map=getMap()
println(“现在发生了”)
}
在这里,您使用的是全局协同路由作用域,因此不会得到任何自动取消。如果你想解决这个问题,就用别的东西代替它