Kotlin协程获取最快的HostUrl

给定一组Host,选出最快的host

1.定义数据源HostInfo

data class HostInfo(var host: String, var time: Int = 0) {
override fun toString(): String {
    return "HostInfo...$host..$time"
}

}

2.模拟一组数据hostList

private val hostList by lazy {
    listOf(
        HostInfo("https://xxx.jshu.com/"),
        HostInfo("https://xxx.wandroid.com/"),
        HostInfo("https://xxx.baidu.com/"),
        HostInfo("https://xxx.h123.com/"),
    )
}

2.采用协程发起请求筛选最快host并回调call

private fun requestFastHost(call: (HostInfo?) -> Unit) {
    lifecycleScope.launch(Dispatchers.IO) {
        hostList.map {
            async{
                //模拟耗时
                val time = Random().nextInt(500)
                return@async it.apply {
                    this.time = time
                }
            }
        }.awaitAll().filter {
            println(it)
            it.time > 0
        }.minByOrNull {
            it.time
        }.apply(call)
    }
}

3、Use

requestFastHost {
  ALog.log("hostList....minTime...$it}")
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容