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

withContext(Dispatchers.IO) how to use for room

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

在道中

  @Query("SELECT * FROM VISITS")
    suspend fun getAllVisits(): List<Visits>

我们正在变成这样

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

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

}

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

你可以使用这样的东西

GlobalScope.launch { 
            withContext(Dispatchers.IO){
                // your query
            }
        }

如果您需要协程作用域来启动协程,您可以根据需要使用 lifecycleScopeviewModelScope

在 Activity 内:

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

片段内:

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

在 ViewModel 中:

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

常规内class:

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()
    }
}

在视图模型中:

viewmodelScope.launch(Dispatchers.IO){
  visitsDao.getAllVisits()
}

或另一个挂起函数

suspend fun addAll() {
    visitsDao.getAllVisits().run{
     ArrayList<Visits>().addAll(this)

   }
}

甚至更多,就用flow,用livedata就可以了builder/map/asLiveData等等