suspend{}协程线程问题
来源:11-5 Kotlin 协程的基本要素1

qq_愿得一人心_28
2020-10-27
fun createCoroutineTest(){
suspend {
//val foo=foo()
try {
val name = getMessageFromNetwork()
Toast.makeText(App.instance.applicationContext,name,Toast.LENGTH_SHORT).show()
//System.err: java.lang.RuntimeException: Can't toast on a thread that has not called Looper.prepare()
}catch (e:Exception){
e.printStackTrace()
//Toast.makeText(App.instance.applicationContext,"success",Toast.LENGTH_SHORT).show()
}
}.createCoroutine(object : Continuation<Unit>{
override val context=EmptyCoroutineContext
override fun resumeWith(result: Result<Unit>) {
Log.d("TAG","Coroutine End with${result}")
//Toast.makeText(App.instance.applicationContext,"$result",Toast.LENGTH_SHORT).show()
// Caused by: java.lang.RuntimeException: Can't toast on a thread that has not called Looper.prepare()
}
}).resume(Unit)
//调用协程就能启动协程了
}
/**
* 从服务器取信息
*/
private suspend fun getMessageFromNetwork(): String {
var name = ""
withContext(Dispatchers.IO) {
delay(3000)
name = "success"
}
if (""==name){
throw IllegalArgumentException("加载失败啦")
}
return name
}
使用 suspend {}.resume() suspend {}.startCoroutine{}两种方式启动协程,suspend {} 和resumeWith(result: Result) {}里面都是子线程,怎么把结果切回主线程上面呢?
写回答
2回答
-
bennyhuo
2020-10-28
慢慢往后看,都会讲到的
00 -
bennyhuo
2020-10-28
底层协程api要手动切的,你也可以用拦截器切
022020-11-03
相似问题
关于协程和线程的一些问题
回答 2
守护线程那里没搞懂。
回答 1