协程-超时

2024-04-16  本文已影响0人  yunhen
fun testTimeout(timeMillis:Long,sleepTime :Long){
    val scope = MainScope()
    val ceh = CoroutineExceptionHandler { _, throwable ->
        when(throwable){
            is CancellationException ->{
                Log.e("testTimeout"," CancellationException ")
            }
            else -> {
                Log.e("testTimeout","throwable${throwable.message}")
            }
        }


    }
    scope.launch(ceh) {
        withContext(Dispatchers.IO){
            val s = withTimeoutOrNull(timeMillis){
                return@withTimeoutOrNull suspendCancellableCoroutine<Boolean> {continuation ->
                    Log.e("suspendCancellableCoroutine"," 1 ")
                    SystemClock.sleep(sleepTime)
                    if (continuation.isActive)
                        continuation.resume(true)
                    else
                        continuation.cancel()
                    Log.e("suspendCancellableCoroutine"," 2 ")

                }
            }

            when(s){
                null ->{
                    Log.e(MainActivity.TAG,"超时了!")
                }
                true ->{Log.e(MainActivity.TAG,"没超时 true")}
                else ->{Log.e(MainActivity.TAG,"超时? else ")}
            }
        }
    }
}
上一篇下一篇

猜你喜欢

热点阅读