[英]I am confused with how lifecycleScope in android studio works
I am confused about how flow.collect works.我对 flow.collect 的工作方式感到困惑。 Because in the lifecycleScope below I already say that a should be assigned by the value of data in my database.
因为在下面的生命周期范围中,我已经说过 a 应该由我的数据库中的数据值分配。 However, the value of a is still the string of "Hi" instead of "Hello".
但是,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)
}
}
this is all of the information in my database这是我数据库中的所有信息
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: LifecycleScope.launch 将启动一个协程,为简单起见,lifecycleScope.launch 中的代码将在另一个线程中执行,插入数据并从数据库中读取数据需要一些时间,但println(a)在主线程上,所以它将在此行之前执行a = it[it.size - 1].name ,因此您的println(a)应该像这样在生命周期范围内:
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)
}
}
}
}
Note: take a look on kotlin coroutines to better understand注意:查看 kotlin 协程以更好地理解
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.