withContext(Dispatchers.IO) 如何使用房间

bak*_*ain 3 android kotlin android-room kotlin-coroutines

在我们的应用程序中有很多查询,现在我们正在使用 ROOM ,我想确认在我们这样使用之前使用 Coroutine 的正确方法是什么

于道

  @Query("SELECT * FROM VISITS")
    suspend fun getAllVisits(): List<Visits>
Run Code Online (Sandbox Code Playgroud)

我们变得这样

fun getAll(visit: Visits?) = runBlocking {
        Log.i(TAG, "addOrUpdateRecord")
        try {

val list = ArrayList<Visits>()
                list.addAll(async {
                    visitsDao.getAllVisits()
                }.await())

}
Run Code Online (Sandbox Code Playgroud)

但在一些文章中,我读到运行阻塞仅用于测试而不是生产,请指导我正确的方法谢谢

Gle*_*val 5

如果您需要协程作用域来启动协程,您可以根据需要使用lifecycleScope或准备使用。viewModelScope

在活动内部:

fun myMethod() {
    lifecycleScope.launch {
        val list = visitsDao.getAllVisits()
        //Do something with list here
            ...
    }
}
Run Code Online (Sandbox Code Playgroud)

片段内部:

fun myMethod() {
    viewLifecycleOwner.lifecycleScope.launch {
        val list = visitsDao.getAllVisits()
        //Do something with list here
            ...
    }
}
Run Code Online (Sandbox Code Playgroud)

在 ViewModel 内部:

fun myMethod() {
    viewModelScope.launch {
        val list = visitsDao.getAllVisits()
        //Do something with list here
        ...
    }
}
Run Code Online (Sandbox Code Playgroud)

普通班级内:

class MyPresenter: CoroutineScope {
    private val myJob = Job()
    override val coroutineContext: CoroutineContext
        get() = Dispatchers.Default + myJob
    
    ...

    fun myMethod() {
        launch {
            val list = visitsDao.getAllVisits()
            //Do something with list here
            ...
        }
    }
    
    ...

    //Call clear when required
    fun clear() {
        this.myJob.cancel()
    }
}
Run Code Online (Sandbox Code Playgroud)