如何解决为什么调用lifecycleScope.launch {//与数据库进行交互}起作用不破坏协程上下文,会创建新线程吗?
我对以下代码为何起作用(从MainActivity调用)感到困惑:
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
log(Thread.currentThread().name) //main
lifecycleScope.launch {
interactWithDatabase()
}
}
suspend fun interactWithDatabase(){
log(Thread.currentThread().name) //main
NoteDatabase(this).getNoteDao().addNote(Note(id=0,title = "TITLE",note = "BODY"))
//signature of addNote: @Insert suspend fun addNote(note: Note)
textView.text = "TEST" //making sure I can update the UI
}
“主”打印两次。
如果方法addNote不是“可暂停的”,则出现以下异常:
java.lang.IllegalStateException: Cannot access database on the main thread since it may potentially lock the UI for a long period of time.
这使我相信将“ addNote”设置为可暂停意味着在调用该方法时会创建一个新线程。 (可能不是这种情况,但是我想不出另一种解释。如果我们停留在主线程上,并且主线程像Executors.newSingleThreadExecutor()一样工作,它最终仍将在主线程上运行并保持正确调用onDraw吗?)
以下内容使我更加困惑:
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
log(Thread.currentThread().name) //main
lifecycleScope.launch(**Dispatchers.IO**){
interactWithDatabase()
}
NavigationUI.setupActionBarWithNavController(this,navController)
}
suspend fun interactWithDatabase(){
log(Thread.currentThread().name) //DefaultDispatcher-worker-1
NoteDatabase(this).getNoteDao().addNote(Note(id=0,note = "BODY"))
//signature of addNote: @Insert suspend fun addNote(note: Note)
textView.text = "TEST" //actually updates the UI
}
为什么允许从非主线程“ DefaultDispatcher-worker-1”更改textView.text?
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。