Kotlin根据请求检测超时



嗨,我仍然是Kotlin语言的新手,例如在Java中向服务器请求数据时:

try{
    request_server();
}
catch(IOException e){
    //Some toast for network timeout for example
}

如何检查该请求是否在Kotlin中有网络超时?

kotlin没有检查异常,但这并不意味着您无法在Kotlin中捕获IOException。除了 catch中的变量声明:

中没有区别
try{
    request_server();
}
catch(e: IOException){
    //Some toast for network timeout for example
}

不过,您很少见到这种语言的构造。由于Kotlin对高阶功能有很好的支持,因此您可以将错误处理中提取到此类功能中,并使业务逻辑更加明显并启用重复使用。

fun <R> timeoutHandled(block: () -> R): R {
    try {
        return block()
    } catch (e: IOException) {
        //Some toast for network timeout for example
    }
}

这样使用:

val result = timeoutHandled {
    requestServer()
}

最新更新