到目前为止,每当我想访问数据库时,我都会使用这种模式:
runBlocking {
launch {
// fetch something from the database and put it to some view
}
}
现在,我正在深入研究Kotlin 合作项目,我越来越确信,这是一种糟糕的模式.基本上,我可能只有allowMainThreadQueries
个,因为我的模式无论如何都会阻塞主线程.
不幸的是,我还没有找到一个合适的模式.如何有效地使用Kotlins协程来访问数据库?
runBlocking
是合作项目的唯一入口吗?
考虑以下情况:
override fun onCreate() {
setContentView(someLayout)
// concurrently fetch something from the database and put it in some view
// onCreate may return before this has finished
someButton.setOnClickListener {
// concurrently insert or update something in the database
}
}