关于android:协程暂停功能和阻止调用

Coroutine suspend function and blocking calls

下面是我的用例。
我有一个函数fun requestFocus,此函数依次调用函数fun configure,该函数依赖于系统中的回调,因此此函数configure使用带有计数1的coundownlatch,并等待直到收到回调时将其重置为零。
为此,我已将requestFocus标记为suspend,并使用Dispatchers.IO进行所有操作。
现在,前一个功能fun accept有多个requestFocus调用方。该函数accept做很多事情,并且所有这些事情都发生在同一线程上。函数accept也可以从主线程或意图服务中调用。我的问题是,因为函数configure阻塞了,所以我不想阻塞主线程。
当前接受函数如下所示:

1
2
3
4
5
fun accept() {
    //do something
    requestFocus()
    // do something
}

我不确定如何才能从accept调用requestFocus,并确保在requestFocus执行后发生的所有操作都以相同的方式发生。我目前在接受功能中所做的工作如下

1
2
3
4
5
6
fun accept() {
    //do something
    runBlocking{
    requestFocus()
    // do something
}

但是这会导致问题,因为主线程被阻塞了。有什么建议可以尝试吗?我已经研究了全球范围和主要范围的文档。


您正在寻找withContext块。 withContext的行为类似于runBlocking,但是它挂起线程而不是阻塞线程。

1
2
3
4
5
6
7
8
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创建协程以启动协程:

1
2
3
4
5
6
7
8
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
}