Mar*_*ark 3 kotlin kotlinx.coroutines
在设计带有suspend
函数的API时,有时我想传达这个函数应该被调用,比如IO线程.其他时候必须这样做.
通常看起来很明显; 例如,应该使用数据库调用,Dispatchers.IO
但如果它是一个接口函数,则调用者不能假设这一点.
这里最好的方法是什么?
如果suspend
函数确实必须在特定上下文中运行,则直接在函数体中声明它.
suspend fun doInIO() = withContext(Dispatchers.IO) {
}
Run Code Online (Sandbox Code Playgroud)
如果调用者应该能够更改调度程序,则该函数可以将调度程序添加为默认参数.
suspend fun doInIO(context: CoroutineContext = Dispatchers.IO) = withContext(context) {
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
469 次 |
最近记录: |