我对Android Studio中的LifeCyclescope感到困惑
我对flow的方式感到困惑。因为在下面的LifecyClesCope中,我已经说过A应该由数据库中的数据值分配。但是,A的值仍然是“ HI”的字符串,而不是“ Hello”。
class MainActivity : AppCompatActivity() {
private var binding: ActivityMainBinding? = null
private var a: String = "Hi"
override fun onCreate(savedInstanceState: Bundle?) {
binding = ActivityMainBinding.inflate(layoutInflater)
super.onCreate(savedInstanceState)
setContentView(binding?.root)
val somethingDao = SomethingDatabase.getDatabase(this).somethingDao()
lifecycleScope.launch {
somethingDao.insert(SomethingModel("Hello"))
somethingDao.fetchAllSomething().collect {
a = it[it.size - 1].name
}
}
println(a)
}
}
所有信息
这是我数据库中的
I am confused about how flow.collect works. Because in the lifecycleScope below I already say that a should be assigned by the value of data in my database. However, the value of a is still the string of "Hi" instead of "Hello".
class MainActivity : AppCompatActivity() {
private var binding: ActivityMainBinding? = null
private var a: String = "Hi"
override fun onCreate(savedInstanceState: Bundle?) {
binding = ActivityMainBinding.inflate(layoutInflater)
super.onCreate(savedInstanceState)
setContentView(binding?.root)
val somethingDao = SomethingDatabase.getDatabase(this).somethingDao()
lifecycleScope.launch {
somethingDao.insert(SomethingModel("Hello"))
somethingDao.fetchAllSomething().collect {
a = it[it.size - 1].name
}
}
println(a)
}
}
this is all of the information in my database
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
lifecyclescope.launch将启动一个coroutine,以使其简单,以使lifecyclescope.launch中的代码将在另一个线程中执行,它将需要一些时间直到插入数据并从数据库中读取它,但是 println(a)在主线程上,因此将在此行之前执行 a = it [it.size -1] .name ,因此您的 println(a)应该在内部 lifecyclescope.launch 这样:
注意:看看Kotlin Coroutines以更好地理解
lifecycleScope.launch will start a coroutine, to make it simple the code inside lifecycleScope.launch will be executed in another thread and it will take some time until inserting data and reading it from database, but println(a) is on the main thread so it will be executed before this line a = it[it.size - 1].name, so your println(a) should be inside lifecycleScope.launch like this:
Note: take a look on kotlin coroutines to better understand