给定一个类似树的结构,以及一个获取节点子节点的操作,例如:
typealias NodeReference = URL
data class Node(
val data:Data,
val childrenList:List<NodeReference>)
suspend fun resolve(nodeRef:NodeReference) : Node 您知道实现具有签名的爬虫功能的蓝图吗?
fun nodeList(rootNode:NodeReference) : List<Node> =
runBlocking(...) {
...
}使用Kotlin协同线返回树的所有节点?
发布于 2020-04-04 19:58:42
要有效地解决这个问题,您应该:
rootNode: Node
rootRef: NodeReference以异步调用results
rootNode
children的nodeList方法--结果,并向其添加以下是您可以这样做的方法:
suspend fun nodesList(rootRef: NodeReference): List<Node> = coroutineScope {
val rootNode = resolve(rootRef) // 1
rootNode.childrenList
.map { async { nodesList(it) } } // 2
.awaitAll() // 3
.flatten() + rootNode // 4
}如果要使用当前线程执行nodesList,可以按以下方式执行:
fun nodesListBlocking(rootRef: NodeReference): List<Node> = runBlocking { nodesList(rootRef) }https://stackoverflow.com/questions/61031827
复制相似问题