在声明挂起功能时传达预期的线程类型(IO,默认,main)

Mar*_*ark 3 kotlin kotlinx.coroutines

在设计带有suspend函数的API时,有时我想传达这个函数应该被调用,比如IO线程.其他时候必须这样做.

通常看起来很明显; 例如,应该使用数据库调用,Dispatchers.IO但如果它是一个接口函数,则调用者不能假设这一点.

这里最好的方法是什么?

Ren*_*ene 8

如果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)