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

猜你喜欢

转载自blog.csdn.net/mp624183768/article/details/126446838