我正在使用Kotlin Coroutines执行异步网络操作以避免NetworkOnMainThreadException
。
问题是当我使用runBlocking
时发生的延迟,这需要一段时间才能完成当前线程。
我如何防止这种延迟或延迟,并允许异步操作无延迟地完成
runBlocking {
val job = async (Dispatchers.IO) {
try{
//Network operations are here
}catch(){
}
}
}
答案 0 :(得分:2)
通过使用runBlocking
,您将阻塞主线程,直到协程完成。
不会抛出NetworkOnMainThread
异常,因为从技术上讲,请求是在后台线程上完成的,但是通过使主线程等待直到后台线程完成,这同样很糟糕!
要解决此问题,您可以launch
协程,并且可以在协程内部完成取决于网络请求的任何代码。这样,代码仍可以在主线程上执行,但绝不会阻塞。
// put this scope in your activity or fragment so you can cancel it in onDestroy()
val scope = MainScope()
// launch coroutine within scope
scope.launch(Dispachers.Main) {
try {
val result = withContext(Dispachters.IO) {
// do blocking networking on IO thread
""
}
// now back on the main thread and we can use 'result'. But it never blocked!
} catch(e: Exception) {
}
}
如果您不关心结果,而只想在其他线程上运行一些代码,则可以简化为:
GlobalScope.launch(Dispatchers.IO) {
try {
// code on io thread
} catch(e: Exception) {
}
}
注意:如果您正在使用封闭类中的变量或方法,则仍应使用自己的作用域,以便可以及时取消它。