0
点赞
收藏
分享

微信扫一扫

Android 协程 超时任务


/**
* 超时任务
*/
@Test
fun `test deal with timeout`() = runBlocking<Unit> {
withTimeout(1300) {
repeat(1000) { i ->
println("job:I'm sleeping $i ...")
delay(500)

}
}
}


时间不够会自动抛出异常退出


 可以使用withnull拿到结果

/**
* 超时任务
*/
@Test
fun `test deal with timeout return null`() = runBlocking<Unit> {
//时间不够会自动抛出异常退出
val res=withTimeoutOrNull(1300) {
repeat(2) { i ->
println("job:I'm sleeping $i ...")
delay(500)
}
"done"
}
println(res)
}

2次的重复肯定是返回done 如果三次则返回null

举报

相关推荐

Android协程的使用

0 条评论