tomcat启动设备未就绪
Launching suspend
functions in Kotlin can be a complicated affair. Managing your CoroutineScope
and making sure exceptions are handled properly can be confusing and easy to forget.
在Kotlin中启动suspend
功能可能很复杂。 管理您的CoroutineScope
并确保正确处理了异常会造成混乱,并且容易忘记。
In Android, when using the ViewModel
or Lifecycle
specific scopes this gets much easier. We let the Android system provide a CoroutineScope
and manage killing our coroutines when the lifecycle of those things end.
在Android中,使用ViewModel
或Lifecycle
特定范围时,这变得容易得多。 我们让Android系统提供一个CoroutineScope
并在这些生命周期结束时管理杀死我们的协程。
fun getObjectFromNetwork() {
viewModelScope.launch {
val response = networkRepository.getObject()
}
}
However, there are cases when exceptions can be thrown from the CoroutineScope
. A real life example I experienced recently was a SocketTimeoutException
that was thrown from a Retrofit call I was making using a suspend
function. The result is an Android app crash, which is definitely not desired when network calls can result in many different thrown exceptions.
但是,在某些情况下,可以从CoroutineScope
抛出异常。 我最近遇到的一个现实生活中的例子是SocketTimeoutException
,它是我通过使用suspend
函数进行的Retrofit调用引发的。 结果是Android应用程序崩溃 ,当网络调用会导致许多不同的引发异常时,绝对不希望