给定一组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}")
}