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 ")}
}
}
}
}
网友评论