[英]Inappropriate blocking method call, but Suspend function 'withContext' should be called only from a coroutine or another suspend function
[英]Coroutine suspend function and blocking calls
下面是我的用例。 我有一个函数fun requestFocus
这个函数又调用函数fun configure
,它取决于来自系统的回调,因此这个函数configure使用计数为 1 的 coudownlatch 并等待直到它在收到回调时重置为零。 为此,我已将requestFocus
标记为挂起并使用 Dispatchers.IO 来完成其所有操作。 现在有多个requestFocus调用者用于 ex 函数fun accept
。 函数accept做了很多事情,所有这些都发生在同一个线程上。 函数accept也可以从主线程或意图服务调用。 我的问题是因为函数 configure 正在阻塞我不想阻塞主线程。 目前接受功能看起来像这样
fun accept() {
//do something
requestFocus()
// do something
}
我不确定如何从 accept 调用 requestFocus 并使 requestFocus 执行后发生的所有操作以相同的方式发生。 我目前在接受功能中所做的如下
fun accept() {
//do something
runBlocking{
requestFocus()
// do something
}
但这会产生问题,因为主线程被阻塞。 任何建议我可以尝试什么? 我查看了全局范围和主要范围的文档。
您正在寻找withContext
块。 withContext
行为类似于runBlocking
但它挂起线程而不是阻塞它。
suspend fun accept() {
//do something on calling thread
withContext(Dispatchers.IO){ // Changes to Dispatchers.IO and suspends the calling thread
requestFocus() // Calls requestFocus() on Dispatchers.IO
// do something on Dispatchers.IO
}
// Resumes calling thread
}
您需要从协程范围或另一个挂起函数调用accept
。 或者你可以创建一个带有launch
的协程来启动一个协程:
fun accept() = launch(Dispatchers.Main) { // Starts a coroutine on the main thread
//do something on main thread
withContext(Dispatchers.IO){ // Changes to Dispatchers.IO and suspends the main thread
requestFocus() // Calls requestFocus() on Dispatchers.IO
// do something on Dispatchers.IO
}
// Resumes main thread
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.