例如,从暂停功能起,我们如何启动协程以触发并忘记http请求?也就是说,启动协程的挂起函数可以返回,而http请求可能正在进行中。 (例如,触发带有副作用的http请求以捕获分析/指标)。
答案 0 :(得分:1)
如果您只是想抛弃协程,甚至不需要暂停功能。您可以只使用GlobalScope
fun test() {
GlobalScope.launch {
while (true) {
delay(1000)
println("I'm alive")
}
}
}
答案 1 :(得分:1)
检查此:
fun ABC(){
GlobalScope.launch(Dispatchers.IO) {
try {
while (true) {
delay(10000)
}
} catch (e: Exception) {
Timber.e(e)
}
}
答案 2 :(得分:-1)
一旦您位于协程内部,则应仅将暂停函数的返回类型保存在变量中,仅此而已。
例如,如果您这样做:
coroutineScope.launch{
thisIsASuspendingMethod()
thisIsAlsoASuspendingMethod()
}
没有人能保证您第一个方法将首先结束其执行,因为suspend
方法就是这样做,会运行缓慢的代码。
但是,如果您使用:
coroutineScope.launch{
val retreiveData = thisIsASuspendingMethod()
if(retreiveData.isSucessful()){
thisIsAlsoASuspendingMethod()
}
}
此外,我建议您阅读有关协程的更多信息,仅因为您发表以下声明:
例如,从暂停功能中,我们如何启动协程 触发并忘记http请求
协同程序是为了运行suspend
方法而启动的,否则不是这样。
由于协程仅运行慢速代码,因此您可能需要考虑在暂挂方法中使用暂挂方法。